2017-10-12 20 views
-1

エラーが発生しています。ブロックなしで終了する場合は、VBAを初めて使用していて、他のスレッドの回答を自分の運には適用しませんでした。手伝ってくれませんか。あなたは、コード自体が再び作業を行っている正確なイベントを発生させ、細胞、に変更を加えているので、コードの中Eventsをオフにする必要が一度だけ、この火災を確実にするために、事前VBA終了ブロックなしブロックの場合

Private Sub Worksheet_Change(ByVal Target As Range) 
    Dim KeyCells As Range 

    ' The variable KeyCells contains the cells that will 
    ' cause an alert when they are changed. 
    Set KeyCells = Range("B2:B6") 

    If Not Application.Intersect(KeyCells, Range(Target.Address)) _ 
      Is Nothing Then 

     ' Display a message when one of the designated cells has been 
     ' changed. 
     ' Place your code here. 
     MsgBox "Cell " & Target.Address & " has changed." 
     For Each KeyCells In Range(Target.Address) 
     If KeyCells.Value <> "" Then KeyCells.Value = KeyCells.Value & "-CN" 
     Next 
    End If 
End Sub 
+2

あなたが投稿したコードは構文的にうまく、エラーなくコンパイルされます。それは無限ループにつながるので、良いコードではありません - イベントを無効にする必要があります! – Rory

+0

@Roryと同意しますが、コードでは無限ループが発生します。私はB2を変更し、「OK」をクリックするたびに、変更されたセルに '-CN'を入力するとワークシートの変更イベントが発生し、このコードが再度実行されます。 – Kyle

+0

Forループを1回だけ変更するにはどうすればよいですか? –

答えて

1

で 感謝。

Private Sub Worksheet_Change(ByVal Target As Range) 

    Dim KeyCells As Range 

    ' The variable KeyCells contains the cells that will 
    ' cause an alert when they are changed. 
    Set KeyCells = Range("B2:B6") 

    If Not Application.Intersect(KeyCells, Target) _ 
      Is Nothing Then 'since Target is range it will suffice here 


     MsgBox "Cell " & Target.Address & " has changed." 

     Application.EnableEvents = False 'turn off events to avoid endless loop 

     For Each KeyCells In Range(Target.Address) 
      If KeyCells.Value <> "" Then KeyCells.Value = KeyCells.Value & "-CN" 
     Next 

     Application.EnableEvents = True 'turn back on so events continue to fire 

    End If 

End Sub 
関連する問題