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

问题描述 投票:0回答:1

我试图通过Excel工作簿中的所有工作表运行宏。我有下面的代码,但我得到一个运行时错误'1004':对象_Global的方法'联盟'失败了。

我已查找错误,并尝试“进入工具/选项并从下面的建议中选择要求变量声明”选项,但它不起作用。

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
vba for-loop worksheet
1个回答
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,你不能这样做。

© www.soinside.com 2019 - 2024. All rights reserved.