简体   繁体   English

在excel vba消息框中是否可以使用vba语法来强制用户单击“确定”或关闭excel?

[英]Is there a vba syntax to use within excel vba message boxes to force the user to click OK or have excel close?

I am setting-up an excel spreadsheet and I want to force the user to either accept the terms of service with OK within a message Box or have the program close with Cancel. 我正在设置一个Excel电子表格,我想强制用户或者在消息框中单击“确定”接受服务条款,或者单击“取消”关闭该程序。 I am working within visual basic. 我在Visual Basic中工作。 I also placed the "terms" Macro within the workbook. 我还将“术语”宏放在工作簿中。

Well, I did it the wrong way and locked myself of of my own program. 好吧,我做错了办法,把自己锁在了自己的程序里。 I keep reworking the code but I can't get it to pull together. 我一直在重新编写代码,但无法将它们组合在一起。

Sub terms()

MsgBox Prompt:="By using this program, the user agrees to all Terms and Conditions as set forth herein. Click OK to accept and continue, or cancel to exit program.", Buttons:=vbOKCancel + vbExclamation, Title:="User Agreement:"

Dim Answer As VbMsgBoxResult
If Answer = vbCancel Then Workbooks.Close
If vbOK Then Workbooks.Open
End Sub

In the workbook I put the following code: 在工作簿中,我输入了以下代码:

Private Sub Workbook_Open()
terms
End Sub

I was expecting the program to close if the user clicked "Cancel" and the program to open if they clicked OK. 我期望如果用户单击“取消”,程序将关闭,如果单击“确定”,程序将打开。 I tried various different approaches and the latest error noted a compiler error saying argument not optional. 我尝试了各种不同的方法,最近的错误指出编译器错误,指出参数不是可选的。

Workbooks is an collection of all Open workbooks. 工作簿是所有Open工作簿的集合。 So the statement Workbooks.Open makes no sense, since all members are already open. 因此,声明Workbooks.Open没有任何意义,因为所有成员均已打开。 The open method adds a specific workbook to the collection in the form Workbooks("c:\\Test\\myspreadsheet.xls").Open (and logically should have been Add not Open but I see where they were coming from) Similarly Workbooks.Close will close all open workbooks, whereas you would probably only want to close the file just opened. open方法以Workbooks(“ c:\\ Test \\ myspreadsheet.xls”)的形式向集合中添加一个特定的工作簿。Open(逻辑上应该是Add not Open,但我知道它们来自何处)。类似的Workbooks.Close将关闭所有打开的工作簿,而您可能只想关闭刚刚打开的文件。

Also to get a reply from a messagebox you must assign a variable to capture that reply - so 另外,要从消息框中获取答复,您还必须分配一个变量以捕获该答复-因此

    answer = msgbox("You sure?",vbyesno)

So what you actually want is 所以你真正想要的是

Sub terms()
Dim msg as string
Dim Answer As VbMsgBoxResult

msg = "By using this program, the user agrees to all Terms and Conditions as set forth herein. Click OK to accept and continue, or cancel to exit program."
Answer = MsgBox(Prompt:=msg, Buttons:=vbOKCancel + vbExclamation, Title:="User Agreement:")


If Answer = vbCancel Then ThisWorkbook.Close

End Sub 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM