简体   繁体   中英

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. I am working within 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. So the statement Workbooks.Open makes no sense, since all members are already 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.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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