消息框vba

请帮助我纠正Excel 2007以下的VBA代码。有人在适合我需要的论坛之一提供了我的代码。 但是我运行这个代码时遇到了一些问题。 由于我不是程序员,所以不能纠正。 所以请帮助克服这一点。

问题是……信息从头到尾不停地popup。 例如:如果单元格“P7”的值达到0以上,说1,我得到popup消息是好的。 但有时单元格的值在1到2,2到2.5或3之间一直保持在0以上,等等,因为单元格值是从其他单元格(实时数据)的计算中导出的。 由于这个,我得到了每个连续增加单元格值的popup消息。 它应该只在单元格值超过0时popup,而不是从0.5到1,1-2,2到2.5或3的每一个进一步的增量…..除了上述问题,我注意到,如果例如单元格值“P7”在0之上越过1.5,并停留在那里,随后“P8”或“P9”或者两者的单元格值都达到0以上,我也得到popup消息“P7”和“P8 “和”P9“而不是”P8“或”P9“。

以下是供您参考的代码。

Private Sub Worksheet_Calculate() 'Dimension variables Dim c As Range, Str1 As String 'Set up a range to loop thru For Each c In Range("P7:P77,S7:S77") 'Test if that cell contains a number >0 If IsNumeric(c.Value) And c.Value > 0 Then 'Which column are we in to calculate 'The offset to column U and decide whether 'to use Buy or Sell as our string Select Case c.Column Case Is = 16 Str1 = "Buy " oset = 5 Case Is = 19 Str1 = "Sell " oset = 2 End Select 'Popup the message box MsgBox Str1 & c.Offset(, oset) End If Next End Sub 

首先,我也不是一个程序员,但是在这里预计编程的某种程度是可以理解的。 为了解决这个问题,它将超越我所担心的第一个基础。 考虑到这一点,这是我对你的问题的答案。

通过做2件事来解决这个问题:

  1. 在变化之前存储范围的状态
  2. 有一个状态表明你已经在这个检查,因此不希望它被再次激活

第1部分存储状态

您检查的范围的状态存储在相同的子例程中,方法是将这些单元格复制到未使用的工作簿部分,或将其作为公共variables存储在de VBA代码中

然后,除了检查If IsNumeric(c.Value) And c.Value > 0 ,还需要检查上次存储的数字是否为<= 0。 所以你的If语句会变成这样:

 If IsNumeric(c.Value) And c.Value > 0 And d.Value <= 0 Then 

d是你的复制单元格。 您需要确定放置这些单元格的位置(最好使用固定偏移量,或者放在同一个单元格中的隐藏表格上!

或者使用一个公共variablespubVar(),其维数为7到77,16到19,可以在Workbook_Open中进行标注:

 If IsNumeric(c.Value) And c.Value > 0 And pubVar(c.Row(), c.Column())<= 0 Then 

现在无论你走到哪一条路线,都需要在脚本的末尾加上一个Range("P7:P77,S7:S77").Copy实际存储单元格的状态, Range("P7:P77,S7:S77").Copy并粘贴到Range(<where you want it>).PasteSpecial ... 或者通过赋值给variables,如Variant

第二部分有状态

要有一个状态,你可以使用一个公共variables,我会采取一个名为booAlreadyChecking的布尔值,并检查该布尔+一个代码,以改变它的值包裹你的当前代码:

 If Not booAlreadyChecking Then 'Check if there is already another check running booAlreadyChecking = True 'Indicate that there is already a check so not another one will be started For Each c In Range("P7:P77,S7:S77") ... Next booAlreadyChecking = False 'Enable a new check once this one is completed End If