2017-06-13 105 views
2
Private Sub Worksheet_Change(ByVal Target As Range) 
    Dim b As Integer 
    b = 0 

    Dim cell As Range 
    Dim rgn As Range 

    Set rgn = Range("f2:f200") 

    For Each cell In rgn 
     If IsEmpty(cell) = False Then 
      b = b + 1 
     End If 
    Next 

    Range("d2").Value = b 
End Sub 

嗨,我在試圖運行以下Excel VBA代碼片時遇到了問題。一個消息框彈出,說有一個Excel VBA「堆棧空間不足」錯誤

「的堆棧空間」

問題行Set rgn = range("f2:f200"),然後另一個消息框會彈出並說

「對象'範圍'的方法'值'失敗「

我不知道什麼是錯......非常感謝您的幫助。

回答

4

的問題是,你正在改變細胞的變化事件,這將再次觸發事件,又一次,又一次......

您需要暫時禁用事件:

Private Sub Worksheet_Change(ByVal Target As Range) 
    Dim b As Integer 
    b = 0 

    Dim cell As Range 
    Dim rgn As Range 

    Set rgn = Range("f2:f200") 

    For Each cell In rgn 
     If IsEmpty(cell) = False Then 
      b = b + 1 
     End If 
    Next 
    Application.Enableevents = False 
    Range("d2").Value = b 
    Application.Enableevents = True 
End Sub 
+0

由於一個邊注:我建議不要使用'Integer',並始終使用'Long'。如果範圍'rgn'發生變化,您將很容易發生溢出。閱讀[這裏](https://stackoverflow.com/a/26409520/3219613)爲什麼使用'Long'而不是'Integer'總是一個好主意。 –

+0

非常感謝!它完全解決了我的問題,並感謝您的解釋和闡述!他們真的很有用! –

相關問題