2017-06-13 75 views
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 
+0

你爲什麼要這樣做?如果我正確地閱讀它,你可以做'If Instr([that formula])<> 0 Then // C.EntireColumn.Insert //C.Offset(0,-1).Value = ...'and因此不必使用'GoTo'(這是避免的最佳做法)。另外,你想檢查整個範圍內的每個單元嗎?從A1開始說AZ1?這很可能是因爲你正在檢查很多單個單元。 – BruceWayne

+4

如果你找到一個包含該文本的單元格,在它之前插入一個列,這意味着下一個循環將再次處理該單元格,並且再一次,等等。 – Rory

+0

@BruceWayne我的'If'語句格式化爲你以前的建議,但問題仍然存在。這只是我最近的一次迭代。 –

回答

0

感謝@Rory指出什麼是導致一個問題,只要邏輯去。我已經重寫了,以避免這種邏輯。下面是更新後的代碼:

Sub CopyWB() 

Application.ScreenUpdating = False 
Application.Calculation = xlCalculationManual 
Application.DisplayStatusBar = False 
Application.EnableEvents = False 

Dim i As Integer 
Dim C, ColRng, pyAddress, cyAddress As Range 
Dim MemAnal, AttAnal As Variant 

Set MemAnal = Worksheets("Membership Analysis") 
Set AttAnal = Worksheets("Attendance Analysis") 

MemAnal.Select 
    Range("E:J").EntireColumn.Insert 
    Range("E1:J1").Value = Array("Site Status", "Org Service Unit", "Org Region", _ 
     "Location State", "Key State", "DOD") 
    Set ColRng = Range(MemAnal.Cells(1, 1), MemAnal.Cells(1, _ 
     MemAnal.UsedRange.Columns.Count)) 
    Set pyAddress = ColRng.Find("Total Member Count using Age Group for YTD", LookIn:=xlValues) 
    Set cyAddress = ColRng.FindNext(pyAddress) 
    pyAddress.EntireColumn.Insert 
    pyAddress.Offset(0, -1).Value = "Teens " & Right(pyAddress.Text, 4) 
    cyAddress.EntireColumn.Insert 
    cyAddress.Offset(0, -1).Value = "Teens " & Right(cyAddress.Text, 4)  

Application.ScreenUpdating = True 
Application.Calculation = xlCalculationAutomatic 
Application.DisplayStatusBar = True 
Application.EnableEvents = True 

End Sub 

應當指出的是,這對我的作品,因爲我碰巧知道,在這個數據,我將永遠只能有這兩個文本實例,但這些實例不斷變化的位置因此需要.Find功能。我只是想了解我最初的做法。