2017-05-08 86 views
1

我有以下的Sub,如果它覆蓋的範圍少於88個單元格,它會很好地工作,否則它會在第88次迭代時失敗。VBA循環在第88次迭代時失敗

Private Sub Worksheet_SelectionChange(ByVal Target As Range) 

If Target.Count = 1 And Target.Row >= 3 And Target.Row <= 30 And Target.Column >= 17 And Target.Column < 22 Then 

    i = Target.Row 

    Dim MergeGroups As Range 
    Dim GroupTable As Range 
    Dim rngStart As Range 
    Dim rngEnd As Range 
    Dim rngToCount As Range 
    Dim CurrentGrp As Range 
    Dim NextGrp As Range 
    Dim NumVals As Integer 

    Set MergeGroups = Range("A1:O1") 
    Set GroupTable = Range("Q2:V2") 
    Set CurrentGrp = Range(Cells(GroupTable.Row, ActiveCell.Column).Address) 
    Set NextGrp = Range(Cells(GroupTable.Row, ActiveCell.Column + 1).Address) 
    Set rngStart = MergeGroups.Find(CurrentGrp.Value) 
    Set rngEnd = MergeGroups.Find(NextGrp.Value) 

    Set rngToCount = Range(Cells(ActiveCell.Row, rngStart.Column), Cells(ActiveCell.Row, rngEnd.Column - 1)) 
    ' rngToCount.Font.Bold = True 

    NumVals = Application.WorksheetFunction.CountA(rngToCount) 

    Cells(i, ActiveCell.Column).Value = NumVals 
    ActiveCell.Offset(1, 0).Select 
    Do While ActiveCell.Column < 21 
     ActiveCell.Offset(-28, 1).Select 
    Loop  

End If 

End Sub 

它是在一個特定的工作表對象,利用該SelectionChange事件。當它失敗時,我收到錯誤消息:

運行時錯誤'-2147417848(80010108)':方法'查找'對象'範圍'失敗。

的問題是與線:

Set rngStart = MergeGroups.Find(CurrentGrp.Value) 

誰能幫我明白爲什麼分運行良好的很小的範圍內,但在其他方面圍繞一個特定的迭代失敗了呢?

+4

您每次在循環中選擇另一個單元時都調用相同的子。您需要知道如何在不使用select的情況下執行此操作,或者在執行循環時禁用事件並在退出子文件之前啓用它們。 –

+0

非常感謝@ Mat'sMug!我必須承認我沒有完全理解答覆,但它使我朝着正確的方向 - [這個鏈接](http://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in- excel-vba-macros)很有幫助,因爲我無法理解「.Select」有什麼壞處。我認爲我現在已經開始工作了,只要我正確地測試了一下,我就會在這裏發佈我的新代碼。 – rngeta453

回答

0

感謝@ Mat的馬克杯告訴我什麼是錯的,this Q&A幫助我說得對。這是修改的代碼:

Sub PleaseWorkThisTime() 

Dim MergeGroups As Range 
Dim GroupTable As Range 
Dim GrpCounts As Range 
Dim rngStart As Range 
Dim rngEnd As Range 
Dim rngToCount As Range 
Dim CurrentGrp As Range 
Dim NextGrp As Range 
Dim NumVals As Integer 

Set MergeGroups = Range("A1:O1") 
Set GroupTable = Range("Q2:V2") 
Set GrpCounts = Range("Q3:U23") 

Dim GrpCount As Range 
For Each GrpCount In GrpCounts 

Set CurrentGrp = Range(Cells(GroupTable.Row, GrpCount.Column).Address) 
Set NextGrp = Range(Cells(GroupTable.Row, GrpCount.Column + 1).Address) 
Set rngStart = MergeGroups.Find(CurrentGrp.Value) 
Set rngEnd = MergeGroups.Find(NextGrp.Value) 
Set rngToCount = Range(Cells(GrpCount.Row, rngStart.Column), Cells(GrpCount.Row, rngEnd.Column - 1)) 

NumVals = Application.WorksheetFunction.CountA(rngToCount) 

GrpCount.Value = NumVals 

Next GrpCount 

End Sub