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

时间:2018-08-29 19:28:46

标签: vba for-loop worksheet

我正在尝试在Excel工作簿中的所有工作表中运行宏。我有下面的代码,但是出现运行时错误'1004':对象'_Global'的方法'Union'失败。

我已经查找了错误,并尝试从下面的建议中“进入工具/选项并选择需要变量声明的选项”,但这没有用。

Method 'Union' of object '_Global' failed on cells that are on the same sheet

下面是我的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

1 个答案:

答案 0 :(得分:1)

看起来您需要先将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