【问题标题】:VBA MsgBox Yes/NoVBA MsgBox 是/否
【发布时间】:2018-12-15 05:05:04
【问题描述】:

当我在消息框提示中选择否时,文档仍会关闭。当我选择否时,我希望它保持打开状态。我不知道该怎么做。谢谢。

Option Explicit

Sub b()

 'declares docX as a document and stores it
  Dim docX As Documents
 'opens the document file
  Application.Documents.Open FileName:="C:\Users\johnr\OneDrive\Documents\CIS 208 VBA\Rimando_Input_Box.docm"

'prompts the user to select either Yes or No
 MsgBox Prompt:="Close document?", _
     Buttons:=vbYesNo
'If the user selects the Yes button then the document closes without making save changes.
 If vbYes Then
     Application.ActiveDocument.Close SaveChanges:=wdPromptToSaveChanges
 Else
     'Keep the document open
 End If

End Sub

【问题讨论】:

    标签: excel vba msgbox


    【解决方案1】:

    那是因为您没有将 msgbox 的值返回给变量。

    在这种情况下,我宁愿不使用变量,而只使用简单的Select Case 语句:

        Select Case MsgBox(Prompt:="Close document?", Buttons:=vbYesNo)
        Case vbYes
             Application.ActiveDocument.Close SaveChanges:=wdPromptToSaveChanges
        Case vbNo
             'Keep the document open
        End Select
    

    但我确实注意到另一个问题,您将docX 声明为类型文档,您可能打算使用Dim docX As Document(不是s)。然后我还注意到你甚至没有使用变量。

    请参阅以下内容以更正这些问题:

    Sub b()
    
        Dim docX As Document
        Set docX = Application.Documents.Open( _
               Filename:="C:\Users\johnr\OneDrive\Documents\CIS 208 VBA\Rimando_Input_Box.docm")
    
        Select Case MsgBox(Prompt:="Close document?", Buttons:=vbYesNo)
        Case vbYes
             docX.Close SaveChanges:=wdPromptToSaveChanges
        Case vbNo
             'Keep the document open
        End If
    
    End Sub
    

    【讨论】:

    • Awww 我要提议If MsgBox(Prompt:="Close document?", Buttons:=vbYesNo) = vbYes Then... :)
    • 哈! - 抱歉 :-)
    猜你喜欢
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多