2016-12-12 49 views
0

我想做一個宏。我的測試單元在另一張紙上。工作表 - (數據)宏檢查範圍("D2:D10")如果單元格包含值12,如果是顯示一個消息框"Go to add to system",並且此宏單元中的宏發現值將設置爲0.如果單元格中包含值,則顯示消息框的宏

我有此代碼,但它沒有'爲我工作我不知道爲什麼。你可以幫我嗎?

Private Sub check(ByVal Target As Range) 
For Each c In Worksheet("data").Range("D2:D10") 
If Range("D2:D10") = 12 Then 
    MsgBox "Go to add to system" 
    Range ("D2:D10").value = 0 
End If 
Next c 
End Sub 
+0

如果多個小區有12個呢?如果找到一個單元格12,您是否想將整個範圍更改爲0? – nightcrawler23

+0

多個或只有一個沒關係 –

+0

@FiínekCahů測試下面我的答案中的代碼,並讓我知道它是否像你想要的那樣工作 –

回答

1

下面的代碼會糾正你的代碼(它會沒有錯誤運行):

Option Explicit 

Private Sub check(ByVal Target As Range) 

Dim c As Range 

For Each c In Worksheets("data").Range("D2:D10") 
    If c.Value = 12 Then 
     MsgBox "Go to add to system" 
     c.Value = 0 
    End If 
Next c 

End Sub 

但是,你可以用一個稍微不同的方式去 - 通過完成您試圖在達到什麼(「數據」表)的事件。

代碼

Option Explicit 

Private Sub Worksheet_Change(ByVal Target As Range) 

Dim c As Range 

' Optional : use if criteria below to check the range only 
' if one of the cells inside range("D2:D10") has changed 
If Not Intersect(Range("D2:D10"), Target) Is Nothing Then 
    ' if you decide to use the "If"above, then you don't need the "For" loop below 
    For Each c In Range("D2:D10") 
     If c.Value = 12 Then 
      MsgBox "Go to add to system" 
      c.Value = 0 
     End If 
    Next c 
End If 

End Sub 
+0

嗨,請你能幫我替換特定單元格的範圍嗎?或者我可以一起使用這兩種方法嗎? thx –

+0

@FiínekCahů什麼是特定細胞?您也可以爲單個單元格使用範圍。 –

+0

不是範圍,而是特定的單元格,例如「D29」,「D55」等。 –

相關問題