简体   繁体   English

Excel VBA在一系列工作簿上遍历工作表

[英]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. 我有一个Master Macro Workbook,其唯一目的是运行一个宏,该宏循环遍历特定文件夹中的所有Workbook,进行大量更改,然后将其保存到其他文件夹中。

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 您没有指向ws的范围

use the . 使用. beforehand otherwise you're referring to the ActiveSheet instead. 否则,您之前是指ActiveSheet

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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