+ Reply to Thread
Results 1 to 8 of 8

For Next Loop

Hybrid View

HangMan For Next Loop 09-07-2015, 10:59 AM
romperstomper Re: For Next Loop 09-07-2015, 11:22 AM
HangMan Re: For Next Loop 09-07-2015, 11:30 AM
jason.b75 Re: For Next Loop 09-07-2015, 12:49 PM
HangMan Re: For Next Loop 09-07-2015, 01:47 PM
jason.b75 Re: For Next Loop 09-07-2015, 03:41 PM
HangMan Re: For Next Loop 09-07-2015, 04:07 PM
jason.b75 Re: For Next Loop 09-07-2015, 04:23 PM
  1. #1
    Forum Contributor
    Join Date
    06-21-2010
    Location
    -
    MS-Off Ver
    Excel 2010
    Posts
    1,211

    Red face For Next Loop

    I have some code which all runs perfectly. I needed to expand the code with a For Next Loop, and so added this, but when I run it the workbook just hangs. Have I set it into an endless loop and what do I need to do to prevent that?

    I'm still very new to VBA and am adding code through trial and error but am unsure where I'm going wrong...

    Added Code

        Dim wb As Workbook
        Dim ws As Worksheet
        Dim varMySheet As Variant
        Dim pt As PivotTable, arr, rng As Range, i As Long, FName
        
        Dim oChart As ChartObject
        Dim mySrs As Series
    
    
        For Each ws In ActiveWorkbook.Worksheets
            For Each oChart In ws.ChartObjects
                For Each mySrs In oChart.Chart.SeriesCollection
                    mySrs.Formula = WorksheetFunction.Substitute(mySrs.Formula, "[1]", "'My Report'")
                Next
            Next
        Next ws
    Many thanks

  2. #2
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    21,997

    Re: For Next Loop

    Nope there are no endless loops there - that code looks fine. Is there more?
    Everyone who confuses correlation and causation ends up dead.

  3. #3
    Forum Contributor
    Join Date
    06-21-2010
    Location
    -
    MS-Off Ver
    Excel 2010
    Posts
    1,211

    Re: For Next Loop

    This is my entire code, have I made a glaring error. Without the newly added code (highlighted in red) everything runs okay... with the newly added code the Workbook just hangs completely and I have to force quite Excel.

    Sub MyReport()
    
        Dim wb As Workbook
        Dim ws As Worksheet
        Dim varMySheet As Variant
        Dim pt As PivotTable, arr, rng As Range, i As Long, FName
        
        Dim oChart As ChartObject
        Dim mySrs As Series
      
        Application.ScreenUpdating = False
        Application.DisplayAlerts = False
        
        For Each varMySheet In Array("Data", "Lists")
            Sheets(varMySheet).Visible = xlSheetVisible
        Next varMySheet
      
        Set wb = Workbooks.Add
        Set ws = wb.Worksheets(1): arr = Array("My Report", "North", "South", "East", "West", "Pivot", "Data", "Lists")
    
      
        ThisWorkbook.Worksheets(arr).Copy Before:=ws
      
        For i = 1 To UBound(arr) + 1
            For Each pt In Worksheets(i).PivotTables
                ws.Cells.Clear: Set rng = pt.TableRange2: rng.Copy
                ws.Range("A1").PasteSpecial (xlPasteValues)
                ws.Range("A1").PasteSpecial (xlPasteFormats)
                rng.Clear: ws.Range("A1").CurrentRegion.Copy rng
            Next pt
        Next i
        
        For Each ws In ActiveWorkbook.Worksheets
            
            ws.Cells.Copy
            ws.[A1].PasteSpecial Paste:=xlValues
            Application.CutCopyMode = False
            Cells(1, 1).Select
            ws.Activate
        Next ws
        Cells(1, 1).Select
    
      i = UBound(arr) + 2
      
        While wb.Worksheets.Count >= i
        wb.Worksheets(i).Delete: Wend
        
        Worksheets("My Report").Activate
        
        For Each varMySheet In Array("Data", "Lists")
            Sheets(varMySheet).Visible = xlVeryHidden
        Next varMySheet
        
        For Each ws In ActiveWorkbook.Worksheets
            For Each oChart In ws.ChartObjects
                For Each mySrs In oChart.Chart.SeriesCollection
                    mySrs.Formula = WorksheetFunction.Substitute(mySrs.Formula, "[1]", "'My Report'")
                Next
            Next
        Next ws  
        
        ActiveWorkbook.Names("Formula").Delete
        
          
        Application.ScreenUpdating = True
        Application.DisplayAlerts = True
                
        FName = Application.GetSaveAsFilename(InitialFileName:="C:\My Folder\My Report.xlsx", fileFilter:="Excel workbook (*.xlsx), *.xlsx")
        On Error Resume Next: If FName <> False Then wb.SaveAs FName
            
        If Err.Number <> 0 Then
            Application.Dialogs(xlDialogSaveAs).Show
        Err.Clear
            
        End If
        
    End Sub
    Many thanks
    Last edited by HangMan; 09-07-2015 at 06:18 PM.

  4. #4
    Forum Expert
    Join Date
    06-08-2012
    Location
    Left the forum!
    MS-Off Ver
    Left the forum!
    Posts
    5,189

    Re: For Next Loop

    See if setting calculation to manual makes any difference.

    I don't use vba with charts so can't comment on specifics of your code, but standard excel behaviour with automatic calculation would be to recalculate every time the code passes over WorksheetFunction.

    Stepping through the code with f8 and monitoring the values of your variables is sometimes the easiest way to find why your code is running slow or not as expected.

  5. #5
    Forum Contributor
    Join Date
    06-21-2010
    Location
    -
    MS-Off Ver
    Excel 2010
    Posts
    1,211

    Re: For Next Loop

    Without wanting to sound totally stupid, how would I set calculation to manual (or is that what you meant by stepping through the code...) I'm really not so familiar with VBA, I tried stepping through the code but not really sure what I'm looking for to be totally honest.

    The code is basically supposed to change the data source for the charts from the name of the original workbook to the name of the new workbook but when I run it, I just get the hour glass and the main Workbook hangs (not responding). I'm unsure what is causing the problem though.

        For Each ws In ActiveWorkbook.Worksheets
            For Each oChart In ws.ChartObjects
                For Each mySrs In oChart.Chart.SeriesCollection
                    mySrs.Formula = WorksheetFunction.Substitute(mySrs.Formula, "'Original Workbook Name.xlsm'", "'New Workbook Name.xlsx'")
                Next
            Next
        Next ws
    The error I get relates to the line in red and is a run-time error '1004', telling me to verify your formula contains a valid path, workbook, range name and cell reference.

    My source series name is:

    =SERIES(" Total Forecast",{"M1","M2","M3","M4","M5","M6","M7","M8","M9","M10","M11","M12"},'Original Workbook Name.xlsm'!My_Forecast,1)
    and I'm trying to change it to:

    =SERIES(" Total Forecast",{"M1","M2","M3","M4","M5","M6","M7","M8","M9","M10","M11","M12"},'New Workbook Name.xlsx'!My_Forecast,1)
    Not sure if that helps to explain the problem?
    Last edited by HangMan; 09-07-2015 at 01:57 PM.

  6. #6
    Forum Expert
    Join Date
    06-08-2012
    Location
    Left the forum!
    MS-Off Ver
    Left the forum!
    Posts
    5,189

    Re: For Next Loop

    In your main code you have
        Application.ScreenUpdating = False
        Application.DisplayAlerts = False
    which is used to disable a couple of things and make the code run more efficiently, another line you can use here is
    Application.Calculation = xlCalculationManual
    Which turns of automatic calculation, then
    Application.Calculation = xlCalculationAutomatic
    which turns it back on again after the code has finished.

    Also, if your code is ended prematurely (for example, by killing the process when it hangs or ending the code when it errors), these settings do not automatically re-enable, you need to do it manually. These are excel settings, not workbook settings, so closing without saving will not cancel out the original change to disable them. The simple way to do this is with a small piece of code like
    Sub Reset_Stuff()
    With Application
        .EnableEvents = True
        .ScreenUpdating = True
        .Calculation = xlCalculationAutomatic
    End With
    End Sub
    Regarding the runtime error, does the workbook 'New Workbook Name.xlsx' actually exist? If that workbook is not open then you would need to specify the full workbook file path, not just the name.

    See if this extract from PeltierTech (<<link to page) helps, it shows the correct way that the code should be written for what you're trying to do.
    Sub ChangeSeriesFormulaAllChartsAllSheets()
        ''' Do all charts in all sheets
        Dim oWksht As Worksheet
        Dim oChart As ChartObject
        Dim OldString As String, NewString As String
        Dim mySrs As Series
    
        OldString = InputBox("Enter the string to be replaced:", "Enter old string")
    
        If Len(OldString) > 1 Then
            NewString = InputBox("Enter the string to replace " & """" _
                & OldString & """:", "Enter new string")
            For Each oWksht In ActiveWorkbook.Worksheets
                For Each oChart In oWksht.ChartObjects
                    For Each mySrs In oChart.Chart.SeriesCollection
                        mySrs.Formula = WorksheetFunction.Substitute(mySrs.Formula, _
                            OldString, NewString)
                    Next
                Next
            Next
        Else
            MsgBox "Nothing to be replaced.", vbInformation, "Nothing Entered"
        End If
    End Sub
    Hopefully this is of some use. I expect that Rory (romperstomper) will have significantly more knowledge and experience than I do relating to chart use and will (hopefully) provide further assistance.
    Don't be afraid to ask if there is something you don't fully understand.

  7. #7
    Forum Contributor
    Join Date
    06-21-2010
    Location
    -
    MS-Off Ver
    Excel 2010
    Posts
    1,211

    Re: For Next Loop

    Strangely PeltierTech is where I 'borrowed' this bit of code from...

        For Each ws In ActiveWorkbook.Worksheets
            For Each oChart In ws.ChartObjects
                For Each mySrs In oChart.Chart.SeriesCollection
                    mySrs.Formula = WorksheetFunction.Substitute(mySrs.Formula, "'Original Workbook Name.xlsm'", "'New Workbook Name.xlsx'")
                Next
            Next
        Next ws
    With regards your question 'does the workbook 'New Workbook Name.xlsx' actually exist?' I had been thinking about this, the answer is no because the code is designed to create a new workbook and save the file with the name of the new workbook but having said that, my understanding of the code above is that all it should be doing is changing the filename for the data series, as in from:

    =SERIES(" Total Forecast",{"M1","M2","M3","M4","M5","M6","M7","M8","M9","M10","M11","M12"},'Original Workbook Name.xlsm'!My_Forecast,1)
    to

    =SERIES(" Total Forecast",{"M1","M2","M3","M4","M5","M6","M7","M8","M9","M10","M11","M12"},'New Workbook Name.xlsx'!My_Forecast,1)
    before saving the file, so does 'New Workbook.xlsx actually need to exist before the file is saved? If the answer is yes, then does that mean the code needs to sit after

        FName = Application.GetSaveAsFilename(InitialFileName:="C:\My Folder\My Report.xlsx", fileFilter:="Excel workbook (*.xlsx), *.xlsx")
        On Error Resume Next: If FName <> False Then wb.SaveAs FName
            
        If Err.Number <> 0 Then
            Application.Dialogs(xlDialogSaveAs).Show
        Err.Clear
            
        End If
    I'll experiment with some of your suggestions and let you know how I get on. Many thanks for all your very helpful suggestions. It feels as though the code is 95% there but I'm just missing one vital element... I just wish I know what that vital element was.

  8. #8
    Forum Expert
    Join Date
    06-08-2012
    Location
    Left the forum!
    MS-Off Ver
    Left the forum!
    Posts
    5,189

    Re: For Next Loop

    When you run the line to update the formula (chart series) excel will attempt to create and validate the link, if there is nothing there then you will get an error, so ideally you would save the workbook first to create the valid filename, then update the charts.

    You might be able to make it work with something like
    mySrs.Formula = WorksheetFunction.Substitute(mySrs.Formula, "[1]", wb.Name)
    but without testing I'm not certain of that.

    Personally, I would save first to create the new filename and path, then work with that.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. [SOLVED] Find function in nested loop breaking down - not on first time through loop
    By adamstarr12 in forum Excel Programming / VBA / Macros
    Replies: 10
    Last Post: 10-14-2014, 09:32 AM
  2. Find function in nested loop breaking down - not on first time through loop
    By adamstarr12 in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 10-07-2014, 04:59 PM
  3. HOW TO: Pause loop, fix error on a popup UserForm, continue loop
    By AndyMachin in forum Excel Programming / VBA / Macros
    Replies: 9
    Last Post: 06-19-2014, 04:37 PM
  4. Loop through multiple files and call macros (but unable to loop)
    By ryanpetersen in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 05-23-2014, 12:04 PM
  5. [SOLVED] Copy dynamically changing column and Paste using VBA Loop (Loop within Loop)
    By nixon72 in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 02-12-2013, 12:46 PM
  6. Why did an inner loop variable start overwriting the outer loop range suddenly?
    By 111StepsAhead in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 05-16-2012, 03:24 PM
  7. Replies: 0
    Last Post: 07-20-2010, 11:42 AM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1