为什么我的宏的第一行出错了? 'Sub Macro5()'?我之前从未遇到过这样的问题。我觉得它一定很简单。
Sub Macro5()
'
' MacroNew Macro
'
Application.ScreenUpdating = False
Dim j As Integer
Dim k As Integer
Worksheets("Resumen").Activate
Columns("Q:V").EntireColumn.Delete
j = 3
Do While Not IsEmpty(Resumen.Cells(j, "A"))
If Not Resumen.Cells(j, 1).Interior.ColorIndex = xlNone Then
Resumen.Range(.Cells(j, 1), Cells(j, 2)).Delete Shift:=xlToUp
End If
Loop
j = j + 1
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:4)
除非'Resumen'是代号,否则你必须告诉VBE'Resumen'是什么。在这种情况下,我将其声明为工作表对象,并将工作表对象设置为指向运行代码的工作簿中的“Resumen”工作表。这应该运行正常(我也修复了你的无限While循环)。
Sub SomeMacro()
' Name your macros with some kind of informative name
Application.ScreenUpdating = False
' 'k' is never used, delete this.
' Dim k As Integer
Dim Resumen As Worksheet
Set Resumen = ThisWorkbook.Worksheets("Resumen")
' You should avoid activate and select like the plague. Qualify and directly modify instead.
' Worksheets("Resumen").Activate
'
' This reference is unqualified, and operates on the active sheet. Use a qualification instead.
' Columns("Q:V").EntireColumn.Delete
Resumen.Columns("Q:V").EntireColumn.Delete
' Declared j as Long instead of Integer. Otherwise you will eventually hit an overflow error. Always use Long over Integer.
Dim j As Long
j = 3
' If Resumen is a codename (you named the sheet directly using the VBE) then this would work fine
' without first declaring 'Resumen' as a variable, and then setting it properly.
Do While Not IsEmpty(Resumen.Cells(j, "A"))
If Not Resumen.Cells(j, 1).Interior.ColorIndex = xlNone Then
Resumen.Range(Resumen.Cells(j, 1), Resumen.Cells(j, 2)).Delete Shift:=xlToUp
End If
' Moved this within the loop since otherwise you will have an infinite loop
j = j + 1
Loop
' You could also use a with block here instead:
' With Resumen
' Do While Not IsEmpty(.Cells(j, "A"))
' If Not .Cells(j, 1).Interior.ColorIndex = xlNone Then
' .Range(.Cells(j, 1), .Cells(j, 2)).Delete Shift:=xlToUp
' End If
'
' j = j + 1
' Loop
' End With
Application.ScreenUpdating = True
End Sub
答案 1 :(得分:1)
以下几行......
Resumen.Range(.Cells(j, 1), Cells(j, 2)).Delete Shift:=xlToUp
应
Resumen.Range(Resumen.Cells(j, 1), Resumen.Cells(j, 2)).Delete Shift:=xlToUp
。细胞与WITH和End With Block
一起使用