简体   繁体   中英

Excel VBA to loop through Worksheets on a series of Workbooks

I have a Master Macro Workbook thats sole purpose is to run a macro that loops through all Workbooks in a specific folder, makes a bunch of changes, and then saves them off to a different folder.

All of it is working except for some new code where I want to loop through all the different Worksheets. The code simply keeps running the code on the first Worksheet over and over again.

    Sub BlendBCoding()
    Dim Filename, Pathname As String
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim NameOfWorkbook
    Dim cel As Variant
    Dim myrange As Range

    Pathname = ActiveWorkbook.Path & "\ToProcess\"
    Filename = Dir(Pathname & "*.xml")
    Do While Filename <> ""
    Set wb = Workbooks.Open(Pathname & Filename)

    For Each ws In wb.Sheets

    Call DoWork(ws)

    Next

        NameOfWorkbook = Left(ActiveWorkbook.Name, (InStrRev(ActiveWorkbook.Name, ".", -1, vbTextCompare) - 1))
            ActiveWorkbook.SaveAs Filename:= _
        "I:\Common\BlendBCoding\Processed\" & NameOfWorkbook & ".xlsx", FileFormat _
        :=xlOpenXMLWorkbook, CreateBackup:=False

        wb.Close SaveChanges:=False
        Filename = Dir()
    Loop

End Sub

Sub DoWork(ws As Worksheet)
    With ws
        Range("A1:G1").EntireColumn.Insert
        Range("A1").Value = "Scan Components"
        Range("A1").ColumnWidth = 16
        //Blah Blah lots of standard text code cut

        Set myrange = Range("H1:H100")
        myrange.Interior.ColorIndex = xlNone
        For Each cel In myrange
        If Application.WorksheetFunction.CountIf(myrange, cel) > 1 Then
        cel.Interior.ColorIndex = 4
        End If
        Next

        'Set myrange = Range("H2:H25")
        'For Each xCell In myrange
        ' xCell.Value = CDec(xCell.Value)
        ' Next xCell

    End With
End Sub

Any help is greatly appreciated.

You're not pointing to the range in ws

use the . beforehand otherwise you're referring to the ActiveSheet instead.

With ws
        .Range("A1:G1").EntireColumn.Insert
        .Range("A1").Value = "Scan Components"
        .Range("A1").ColumnWidth = 16
        //Blah Blah lots of standard text code cut

        Set myrange = .Range("H1:H100")
        myrange.Interior.ColorIndex = xlNone
        For Each cel In myrange
        If Application.WorksheetFunction.CountIf(myrange, cel) > 1 Then
        cel.Interior.ColorIndex = 4
        End If
        Next


End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM