将相同的宏应用于所有工作表

Applying the same Macro to All Worksheets

我正在尝试 运行 通过 Excel 工作簿中所有工作表的宏。我有下面的代码,但我收到 运行 次错误“1004”:对象“_Global”的方法 'Union' 失败。

我已查找错误并尝试"go into Tools/Options and select the option to Require Variable Declaration"下面的建议,但没有成功。

下面是我的 VBA 代码,它将遍历整个工作表。

    Sub Bagasse_YG_Update()

    Dim rng As Range, column As Long, row As Long
    Dim WS_Count As Integer
    Dim I As Integer

    ' Set WS_Count equal to the number of worksheets in the active
    ' workbook.
    WS_Count = ActiveWorkbook.Worksheets.Count

    ' Begin the loop.
    For I = 1 To WS_Count

    'do whatever you need'
    Sheets(I).Select ' Added this command to loop through the sheets

    Range("A1").Select
    Selection.End(xlDown).Select
    Selection.End(xlDown).Select
    Union(ActiveCell.EntireRow, ActiveCell.Resize(1).Offset   (-1).EntireRow).Copy
    ActiveCell.Resize(1).Offset(1).EntireRow.Insert Shift:=xlDown
    Application.CutCopyMode = False

    For column = 4 To 43
        If (column + 1) Mod 4 > 0 Then
            For row = 1 To 2
                If rng Is Nothing Then
                    Set rng = ActiveCell.Offset(row, column)
                Else
                    Set rng = Union(rng, ActiveCell.Offset(row, column))
                End If
                Next row
            End If
            Next column
            rng.ClearContents

    ActiveCell.End(xlDown).Select
    ActiveCell.End(xlDown).Select
    ActiveCell.Offset(-6).EntireRow.Copy
    ActiveCell.Offset(-5).Select
    ActiveCell.EntireRow.Insert Shift:=xlDown
    Application.CutCopyMode = False



    Dim row2 As Long, column2 As Long
    row2 = -2
    For column2 = 5 To 25 Step 4
        ActiveCell.Offset(row2, column2).Copy
        ActiveSheet.Paste Destination:=ActiveCell.Offset(row2 + 1, column2)
        Next column2

    Next I
  Exit Sub
End Sub

看起来你需要在开始移动到下一个 sheet:

之前将 rng 重置为 Nothing
...
Next column
rng.ClearContents

Set rng = Nothing
...

扩展我的评论:

当您转到 Sheet2 时,这是此循环的第一次迭代

If rng Is Nothing Then
    Set rng = ActiveCell.Offset(row, column)
Else
    Set rng = Union(rng, ActiveCell.Offset(row, column))
End If

将直接转到 Set rng = Union(rng, ActiveCell.Offset(row, column)),因为 rng 未重置为 Nothing。然后它会尝试 Union 跨越两个工作sheet,这是你做不到的。