0
我遇到For Each循環導致Excel掛起的問題。一切工作在下面的代碼,直到我得到For Each C In ColRng
代碼。一旦刪除,一切再次運作。For Each Loop導致Excel掛起
Sub CopyWB()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayStatusBar = False
Application.EnableEvents = False
Dim i As Integer
Dim C As Range
Dim MemAnal, AttAnal As Variant
Dim ColRng As Range
Set MemAnal = Worksheets("Membership Analysis")
Set AttAnal = Worksheets("Attendance Analysis")
MemAnal.Select
Set ColRng = Range(MemAnal.Cells(1, 1), MemAnal.Cells(1, MemAnal.UsedRange.Columns.Count))
Range("E:J").EntireColumn.Insert
Range("E1:J1").Value = Array("Site Status", "Org Service Unit", "Org Region", _
"Location State", "Key State", "DOD")
For Each C In ColRng
If InStr(1, C.Text, "Total Member Count using Age Group for YTD") = 0 Then
GoTo Break
Else
C.EntireColumn.Insert
C.Offset(0, -1).Value = "Teens " & Left(C.Text, 4)
End If
Break:
Next C
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.DisplayStatusBar = True
Application.EnableEvents = True
End Sub
你爲什麼要這樣做?如果我正確地閱讀它,你可以做'If Instr([that formula])<> 0 Then // C.EntireColumn.Insert //C.Offset(0,-1).Value = ...'and因此不必使用'GoTo'(這是避免的最佳做法)。另外,你想檢查整個範圍內的每個單元嗎?從A1開始說AZ1?這很可能是因爲你正在檢查很多單個單元。 – BruceWayne
如果你找到一個包含該文本的單元格,在它之前插入一個列,這意味着下一個循環將再次處理該單元格,並且再一次,等等。 – Rory
@BruceWayne我的'If'語句格式化爲你以前的建議,但問題仍然存在。這只是我最近的一次迭代。 –