【发布时间】:2019-02-04 16:14:43
【问题描述】:
我正在尝试通过 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
【问题讨论】:
-
欢迎来到 Stack Overflow!如果可能的话,这篇文章可能会受益于更详细的运行时错误。是否存在导致错误的关联行?