Message Boxes

Too many choices? Leave out the parts you don't want...keep it simple.



A message box that says "Hello World". Add a title by using MsgBox "Hello World",, "This is my title."
Sub MsgBoxExample1()
 MsgBox "Hello World"
End Sub

Note: An Okay button is added by default as no other button choice (vbYesNo, vbYesNoCancel etc) is offered.

A message box with 2 choices. (vbYesNo) with vbQuestion added for a nicer appearance!
Sub MsgBoxExample2()
 If MsgBox("Choose Yes or No", vbQuestion + vbYesNo) = vbYes Then _
  MsgBox "You pushed Yes" Else MsgBox "You pushed No"
End Sub

Note: Normally a vbYesNo messge box would be something like "Do you want to continue?", then If ... = vbYes Then.... In this case, you won't need the No choice, so you can remove this part - Else MsgBox "You pushed No"

A message box with 3 choices. (vbYesNoCancel)
Sub MsgBoxExample3()
 Select Case MsgBox("ChooseYes, No or Cancel", vbQuestion + vbYesNoCancel)
 Case vbYes: MsgBox "You pushed Yes"
 Case vbNo: MsgBox "You pushed No"
 Case Else: MsgBox "You pushed Cancel"
 End Select
End Sub

Note: Same as above. In a real world situation, you might be asked if you want to apply the code to all sheets etc, so for something like "Do you want to include all sheets?", a choice of Yes or No makes sense. Depending on how your code is written, Case Else (or Case vbCancel) may not be necessary.

For more information, consult your Help files. Keep in mind that a little experimentation and looking at other's peoples code can be a big bonus. Keep in mind that simple code is good code (as long as it works!)



© Copyright andrewsexceltips.net All Rights Reserved.