Excel VBA:MsgBox出现得太早

时间:2018-08-27 16:10:05

标签: excel vba excel-vba

我有一个Worksheet_SelectionChange子,如果选择了第3列中的一个单元格,则会选择sheet2并显示一条消息:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  If Target.Column = 3 Then
    Dim response As VbMsgBoxResult

    Select Case Target.Row
      Case 5:
        Sheets("sheet2").Select
        MsgBox ("Test") 'this msgbox shows up early
        'response = MsgBox("Question here?", vbYesNo, "Question title") 'this msgbox shows up early too

    End Select
  End If

End Sub

但是消息显示得太早-sheet1仍处于活动状态。我该如何解决?

要显示sheet2,我需要首先关闭一个MsgBox窗口,这是不方便的,因为窗口内容已连接到sheet2内容。

编辑:我想我明白了。我的代码中有一个Application.ScreenUpdating = False。不,全部有效。谢谢!

1 个答案:

答案 0 :(得分:1)

您可以这样做,例如:

首先,按此处显示的那样修改Sheet1代码。

'// In Sheet1
Public bShowMessageBox As Boolean

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'//-- Your code here
    Select Case Target.Row
      Case 5:
        Sheets("sheet2").Select
        bShowMessageBox = True
'''        MsgBox ("Test") 'this msgbox shows up early
'''        'response = MsgBox("Question here?", vbYesNo, "Question title") 'this msgbox shows up early too
    End Select
'//-- Your code here
End Sub

Public Sub ShowMessageBox()
    bShowMessageBox = False
    MsgBox ("Test") 'this msgbox shows up early
    'response = MsgBox("Question here?", vbYesNo, "Question title") 'this msgbox shows up early too
End Sub

第二,向Sheet2添加一些代码。

'// In Sheet2
Private Sub Worksheet_Activate()
    If Sheet1.bShowMessageBox Then
        Call Sheet1.ShowMessageBox
    End If
End Sub