MS Access: Enhanced Message Box Replacement

Tuesday, May 20, 2008

Microsoft Access This project provides a custom and enhanced message box replacement for the default MsgBoxfound in Access. A Test database containing all the code for Access 2007/2010/2013 is available at the bottom of this post.
(UPDATED Saturday 21OCT2014 to VERSION 1.10.)

What’s wrong with the default MsgBox

The default message box in Access is sometimes useful to warn, inform or ask confirmation from the user.

Standard MsgBox

It has, however, a few drawbacks:

  • It is bland: the standard message box does not even follow the currently selected Office colour scheme.
  • The amount of text it can display is limited: if you try to display too much text it will be truncated.
  • You can’t copy or save the content of the message.
  • Because popup boxes are viewed as intrusive, people tend not to read them and end-up closing message boxes before they realize they may have contained useful information.
  • They only displays plain text: you cannot format the message to draw attention to the key points.
  • They are blocking, meaning that nothing can happen in the main application while the box is displayed (it can’t even shut down).
  • It will only appear on the monitor that has the main Access application window, even though the message box may have been opened from a form on another monitor.

Sometimes you need to display an important message or require users to make take a decision.
Message boxes are not to be abused but they serve a useful purpose.

An enhanced message box

Rather than using the bland standard message box you can now have something a bit more customized.

Plain Text version of the enhanced custom message box under the Office Blue Colour Scheme:

Plaintex Enhanced Message Box

RichText version of the enhanced custom message box under the Office Black Colour Scheme:

RichText Enhanced Message Box

Here are the features of the enhanced message box:

  • It is entirely compatible with the standard one: just change MsgBox to Box using find and replace should be enough (see tip below to avoid getting strange errors).
  • It allows the user to simply click on a button to copy the content of the message to the clipboard or save it to a text file to a configurable default location.
  • It looks and feels like it belongs to the main application, following its colour scheme.
  • It attempts to prevent users from blindly closing the modal box reading the message: buttons will first be inactive for a configurable amount of time. It’s not a perfect solution, but it is quite effective.
  • There is a RichBox version that can display rich HTML content, not just plain text, so important parts of the message can be formatted in a useful way.
  • It is able to display large amount of data. While it’s not something you usually want, it may be useful for the message box to display more text in some situations (log or tracing information, legal documentation, etc).
  • Rather than sprinkling your code with “& vbCrLf & _” uglies, you can embed newlines in the text itself by using C-style “\n” escape sequences that will automatically be transformed into the appropriate newlines. Makes for clearer code and less typing.
  • Because you get the source, you can easily customise the message box with new icons and colours to better match your overall application’s personality.
  • It is non-blocking: if your application forces users to log-off after a certain amount of inactivity, the enhanced message box will just close rather than prevent Access from shutting down like the standard MsgBox does. Of course, it’s up to you to decide how to handle that gracefully, if at all.
  • It properly displays the expected button captions based on the language of the operating system, so it behaves very much like the default MsgBox (for instance, it will properly display “Cancel” on English systems and “Annuler” on French ones).
  • It also properly plays the system sounds associated with the type of message. You can also enable or disable the sound effect as needed.
  • From of version 1.4, it will display on the correct monitor in a multi-monitor environment.
  • Version 1.7 adds support for Unicode escape sequences within strings to display Unicode characters in the dialog box. This was added following the publication of this article about .Net Strings in VBA.
  • Version 1.10 adds a feature that allows users to dismiss a particular message so it doesn’t appear again.

How to use it

Download the demo database below and copy (drag & drop) the following into your application:

  • the FormDialog form,
  • the Dialog module.

If you rename the FormDialog, make sure you replace any occurrence to it in the code, in particular in the Dialog module.

Since the enhanced message box is just a replacement for the standard one, you just use it like you would use the MsgBox.

    ' Simple use of the Plaintext box
    ' Note the use of n that will be converted into a newline
    Dialog.Box "This is a plaintext message.\nClick OK to dismiss",
               vbOKOnly + vbinformation, _
               "Message Title"
    ' Getting the result back
    Dim dr As vbMsgBoxresult
    dr = Dialog.Box("Are you sure you want to delete?", _
                    vbYesNoCancel + vbQuestion, "Confirm action")
    If (dr = vbYes) Then DeleteRecords
    ' Using named parameters
    Dialog.Box Prompt:="All your bases are belong to us", _
               Buttons:=(vbOkOnly + vbCritical), _
               Title:="Bad error"
    ' Using the RichBox to display simple HTML
    ' The first line will be bold, then the word 'button' will be printed in red
    ' Here the \n will be escaped to '<br/>' tags to simulate newlines.
    Dialog.RichBox "<strong>This is a bold message</strong>.\n" & _
                   "Click the <font color=""#FF0000"">button</font> to dismiss.",
                   vbOKOnly + vbInformation, _
                   "RichText Message Title"


There are a few additional settings that can be used to change the behaviour of the enhanced message boxes.

Custom buttons

You can customise the button labels instead of using the default ones (thanks to Kristjan for the suggestion):

Screenshot of dialog box with custom button labels

    ' Use custom labels. Buttons that are not labelled will not be displayed
    ' The returned value is either vbBt1, vbBt2 or vbBt3
    Dim dr As vbMsgBoxresultEx
    dr = Dialog.Box (Prompt:="This is a custom button label test.",
                     Buttons:=vbCustom + vbInformation, _
                     Title:="A custom message", _
                     LabelButton1:="Hit Button 1!", _
                     LabelButton2:="No!, Me! Me!", _
                     LabelButton3:="Forget it!")
    If (dr = vbBt1) Then Debug.Print "Button 1 pressed!"
    ElseIf (dr = vbBt2) Then Debug.Print "Button 2 pressed!"
    ElseIf (dr = vbBt3) Then Debug.Print "Button 3 pressed!"

Button delay

One is that you can adjust the delay before the buttons become activated.

    ' Use the ButtonDelay to specify the time in seconds before the buttons become activated
    ' The default is 2s. Use 0 to activate the buttons immediately.
    Dialog.Box Prompt:="All your bases are belong to us", _
               Buttons:=(vbOkOnly + vbCritical), _
               Title:="Bad error", _
    ' Change the default delay value.
    ' To disable the activation delay
    Dialog.DefaultButtonDelay = 0
    ' To make the user wait 3 seconds before they can press any button
    Dialog.DefaultButtonDelay = 3


Another one is that you can enable or disable whether beeps should be played or not.

    ' Use AllowBeep to specify whether beeps should be played when the message box opens
    ' By default, they are.
    Dialog.Box Prompt:="All your bases are belong to us", _
               Buttons:=(vbOkOnly + vbCritical), _
               Title:="Bad error", _
    ' Change the default behaviour. This is True by default.
    Dialog.DefaultAllowBeep = False

Hide Buttons

You can also hide the Copy to clipboard and save to File buttons which are normally visible by default.

    ' Use AllowCopyToClipboard and AllowSaveToFile to specify whether to display
    ' the copy to clipboard and save to file buttons.
    ' By default, they are visible, but here we hide them.
    Dialog.Box Prompt:="All your bases are belong to us", _
               Buttons:=(vbOkOnly + vbCritical), _
               Title:="Bad error", _
               AllowCopyToClipboard:=False, _
    ' Change the default behaviour. This is True by default.
    Dialog.DefaultCopyToClipboardAllowed = False
    Dialog.DefaultSaveToFileAllowed = False

Save Folder

It is recommended to set the the folder where we should save the content of the message when the user clicks the Save button on the message box.

    ' Change the save folder.
    ' By default, the text messages will be saved in the same directory as the database.
    ' Here we want them to be saved to a temp directory
    Dialog.DefaultSavedTextFileFolder = "C\:temp"

These few settings make the enhanced message box more customizable.

Raw text and paths

By default, the enhanced dialog box will escape certain sequences in the message to convert them to their printable version:

  • Escape sequences like \n and \t are converted to newlines and tabs spaces
  • Unicode sequences are converted to their symbol: \u20ac is converted to the euro symbol .

If you do not want this behaviour (for instance you need to display data that contains lots of \ characters), use the NoStrEsc option:

    ' By default, all messages are unescaped.
    ' Here however, we want to disable that so we can display
    Dialog.Box Prompt:="A path c:\my\doc\file.doc", _
    ' Change the default behaviour. This is False by default.
    Dialog.DefaultNoStrEsc = True

Alternatively, you can use the helper function dialog.EscBackslash():

    ' Use EscBackslash() when you only want some portion of text
    ' to display '\' correctly, like paths.
    ' Here however, we want to disable that so we can display
    Dialog.Box Prompt:="A path " & EscBackslash("c:\my\doc\file.doc")

Don’t display this message again

Based on suggestions (and on a feature I wanted to implement for a while), I added a way to allow the user to choose not to display a particular message again.

Note that this feature will only work for dialog boxes displaying a single vbOKOnly button. It makes some sense since if you ask the user to choose between multiple actions, you can’t really expect their choice to be the same every time the message is displayed.

To make the dialog box dismissable, you only need to provide it with a unique ID for the message, using the DismissID option:

    ' Use DismissID to allow the user to never show the message again.
    Dialog.Box Prompt:="An annoying warning message", _
               Buttons:= vbOKOnly + vbExclamation


The user can then tick the box and this particular message will never be shown again (unless we reset the setting for it).

To ensure that the user’s choice is remembered even if the Access application is updated, the message’s DismissID is stored in the registry under:
HKCU\Software\VB and VBA Program Settings\<AppFileName>\DialogBox, where <AppFileName> is simply the name of your Access file (without the path).

You can easily re-enable a particular message or all messages from your code:

    ' Re-enable the display of a previously dismissed message:
    Dialog.ResetDismissID "1234ABC"
    ' Re-enable the display of all messages:

Large text

The standard MsgBox cannot display much text. On the other hand, there is no real limitation to the amount of text the Box and RichBox can display.
When the amount of information is too much to fit the maximum allowed size for the message box the text will overflow and can be scrolled up/down as necessary.

Limitations of the RichBox

The RichBox version relies on the normal TextBox control’s ability under Access 2007 to display RichText wich is nothing more than lightweight HTML.
Because font size may be varying a lot in the message, it becomes very difficult to accurately predict the size of the box needed to display the whole message.
Short of implementing a complete HTML engine, we have to rely on some assumptions to display HTML.
The risk is that sometimes the content may not properly fit the TextBox control in some circumstances.
If you use the RichBox, thoroughly try displaying your messages and tweak the HTML as necessary to include additional lines or non-breaking spaces to ensure that the result looks good.
If you don’t overuse font size and don’t display in multiple fonts the RichBox should do the right thing most of the time.
Don’t overuse the RichBox to display colourful messages. There is a fine line between being informative and tasteless. Keep colours and formatting where it is useful.
I think that in most cases, the plain text version Box is more than enough.

How it works

The code makes extensive use of Win32 API calls.
Most of the hard work is done in the FomDialog class form. There is too much there to really go into the details but you are welcome to have a look at the commented code.
The code relies also on a utility function from Stephen Lebans used to calculate the size of of text. I have made some minor modification to that code so I would refer you to his original implementation if you are interested in calculating TextBox sizes for forms or reports.

In the code for the FormDialog, I re-implement some of the expected functionalities of the MsgBox: proper arrangement of the buttons, displaying of the appropriate icon, etc.
Once this is done, we calculate the size of the textbox needed to display the whole of the message.
In the case of RichText, we first use Application.PlainText() to convert the HTML into properly formatted plain text. We then calculate the Textbox size using a slightly larger font than needed as a way to ensure that the content of the RichText message will fit the box in most cases.
Once we know the size of the TextBox, we can easily resize the form to properly display the TextBox.
If there is too much text, we resize the form to its maximum permissible (70% of screen width and 90% of screen height) and change some of the visual cues to let the user know the text is overflowing.

One thing of note is the way the form is kept modal.
Rather than using DoCmd.OpenForm and DoCmd.Close I use the form as a class and create an instance manually (see the code in Dialog.Box and Dialog.Richbox). I keep this instance alive until I got the form’s result back.
If you are interested in knowing how the form is made modal, this is the code in FormDialog.ShowModal() what keeps the form open until the user clicks a button:

    Public Function ShowModal() As VbMsgBoxResult
        ' Here we reset the result for the clicked button such as vbOK, vbYes, etc
        ' This is set in each Button's Click event
        m_Result = -1
        ' Wait for the user to click a button
        Do While (m_Result = -1)
            Sleep 50
        ShowModal = m_Result
    End Function

The Sleep() function is a Win32 API that stops the current process for the given number of milliseconds. This in effects hands back the control to the Operating System for a short time. That way the system is still responsive and does not consume resources when it’s just waiting for user input.

Replacing MsgBox in existing code

As I said above, replacing the standard MsgBox is easy but you need to make sure your search and replace parameters are configured correctly:

Search and replace options

If you’re getting strange compile errors, it may be because you forgot to tick the Find Whole Word Only and some of the strings containing the letter sequence “msgbox” were replaced in the process.

If that’s the case, you can revert the damage by simply doing a search and replace across the whole project on:
VbboxStyle or VbDialog.BoxStyle to be replaced with VbMsgBoxStyle
VbboxResult or VbDialog.BoxResultto be replaced with VbMsgBoxResult

Upgrading from an older version

If you are already using the enhanced DialogBox, upgrading to the newest version is simple.

In your Access application:

  • delete the FormDialog form,
  • delete the Dialog module.
  • delete the API_GetTextMetrics module if you have it (used in versions before 1.5)

Download the new version of the demo database below and open it.

  • drag and drop the `FormDialog to your application
  • drag and drop the Dialog module to your application

That’s all you need to do.

Code and demo database

You can download a database containing all the necessary code as well as a number of tests.
This version contains the database in Microsoft Access accdb format (the code relies on features that don’t exist in pre-2007 versions of Access).


Download Download the (177KB), version 1.10 – 21OCT2014 containing the ACCDB database.

Code Updates

v1.10: 21OCT2014
Corrected minor bugs and added new features:

  • Added dialog.EscPath() to escape paths in your message and display them correctly, as suggested by Mark Singer in comment 115.
  • Added option NoStrEsc to display raw text when you don’t want escape and unicode sequences like ‘\n’ and ‘\u20ac’ to be converted at all in your whole message.
  • Modified the code for FileExists() to avoid the issue raised by Matthias Kläy in comment 116
  • Added option DismissID to allow the user to choose to prevent a message from displaying again (suggested by David Dewick in comment 110).

v1.9: 03FEB2014
Corrected some bugs and added some options:

  • Corrected bugs that would throw exceptions when a message would contain some file path whose ‘\’ would be wrongly interpreted as an escape sequence.
  • Added options to show the buttons for copying the message to the clipboard or saving it to file.

v1.8: 28SEP2013
Resolved some Unicode-related bugs:

  • Corrected bugs that would truncate the strings in the dialog box when they contain some Unicode characters.
  • Corrected bug with copy-to-clipboard that was not copying Unicode text.
  • Corrected bug with copy-to-file that was not saving Unicode text properly.

v1.7: 13SEP2013
Added support for character literals in strings and Unicode escape sequences as supported in .Net strings.
See using .Net strings in VBA for fun an profit for details.

v1.6: 29JUN2013
Corrected issues pointed out by Joseph Strickland (thanks) when running under Office 2010 x64.
Code updated and tested under a Virtual Machine running Win8 x64 and Office 2010 x64.

v1.5: 23JUN2013
Many thanks to contributors Steve Spiller, Jiriki and Kytu for improving and pointing out issues. See details below.

  • Moved the code from the API_GetTextMetrics module into the FormDialog class to reduce the number of necessary files (now only FormDialog and Dialog objects are necessary).
  • Corrected bugs on the test form (button delay and beep options on the form were not wired up correctly in the test form)
  • RichBox was not initialising its buttonDelay correctly, resulting in the first call to use a 0 delay instead of the DefaultButtonDelay value.
  • Corrected bug reported by Jiriki on 06JUN2013 (when the ButtonDelay was set to 0, the dialog would just close the first time the dialog was opened).
  • Focus issues should be solved: the buttons are now properly focused and will behave as the standard dialog box (you can hit ENTER or ESC on the keyboard once the buttons are visible to confirm the default dialog action or cancel it).
  • Addressed parent form focus issue mentioned by KyTu on 19JUN2013: when closing the dialog, the parent form will be properly focused instead of the Navigation Panel.
  • Now supports both x86 and x64 Office systems (32 and 64 bits versions of MSAccess). Many thanks to Steve Spiller for sending me the updated database.

v1.4: 01APR2013
It’s been a while, but at last some improvements and bug fixes!

  • As per Julie B’s comment, updated code to properly display the dialog on the proper monitor in multi-monitor environments.
    The dialog box will open in front of the Access window that currently has focus (assumed to be the one that opened the dialog), so if your application has forms on different monitors, the dialog should open on the right one. If we can’t determine the active window, the dialog box will open in the middle of the monitor containing the main Access application window.
  • Implemented Kristjan’s suggestion regarding the use of custom button labels. See updated description above.
  • Corrected background colours for the dialog box so they correctly match the MS Office theme.
  • Corrected a bug in the code that decided of the correct sound to play.

v1.3: 17MAR2009
Thanks to Henry of for proposing a correction to the default buttons behaviour.

  • Updated behaviour for the default buttons. They are now focused in a way that matches that of the standard msgbox.
  • Reversed the naming of the buttons on the form to make it a bit more consistent with the standard box.

v1.2: 07SEP2008
Thanks to Andy Colonna ( for uncovering the following bugs (check out his free Spell Checker with source code!):

  • Corrected bug in Form_FormDialog.FilenameSanitize() function that would fail to remove all invalid characters for a file name.
  • File name for the saved text message will be truncated to first 32 characters of message box title in Form_FormDialog.MakeFriendlyFileName().
  • Changed the use of FollowHyperlink to ShellExecute to avoid security warning in some instances in Form_FormDialog.btCopyToFile_Click()
  • Corrected twips to pixel conversion bug in API_GetTextMetrics.fTextWidthOrHeight() that would result in an improperly sized dialog box when the text message was too wide.

v1.1: 08AUG2008

  • Corrected code for DefaultButtonDelay (thanks to Geoffrey) (was referencing wrong variable, causing self-referencing code).
  • Corrected code for Box and RichBox to take the DefaultSavedTextFileFolder into account (the path was previously not passed onto the dialog boxes and the text file would always be created in the application folder instead of the one specified by DefaultSavedTextFileFolder)
  • Added license notice at top of source code.

v1.0: 20MAY2008

  • Original version


Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.
Free for re-use in any application or tutorial providing clear credit is made about the origin of the code and a link to this site is prominently displayed where end-users can easily access it.

Entry Filed under  :  .Net,Business,Database,MSAccess,Programming

150 Comments Add your own

  • 1. lars  |  November 20th, 2013 at 5:51 pm

    WOW thx very nice

  • 2. Don  |  November 26th, 2013 at 5:25 am

    Are there flags that we can use to remove the “Clipboard” and “Save Text” icons from the message box?

    Very nice project by the way!

  • 3. David Walsh  |  December 6th, 2013 at 8:39 am

    Very nice work, I can see a lot of work has gone into this, thanks for sharing.

    I hit a small problem when displaying paths e.g. M:\tyres\MasterTables within the message prompt. The UnEscStr function changed the \t to a tab, result was M: yres\MasterTables As I don’t need the escape functionality I replaced f.Prompt = UnEscStr(Prompt, toHtml:=False) with f.Prompt = Prompt and that seems to have solved it.

    Thanks again Dave

  • 4. AZ Dave  |  January 7th, 2014 at 6:49 am

    I recently discovered this great tool. One of the issues I had with xmsgbox was the issue when the user average moved the mouse off the msgbox, it would be minimized and lock up the database. This is more flexible. I have updated to v.1.8

    However, I now seem to have developed an issue that I can’t seem to resolve. Each time I open a new form, I receive the following error message: “NAMEDATABASE cannot follow hyperlink to ‘000000’ Please verify destination” he problem is that there are no hyperlinked fields in this database. I do updates and programming at home and at the office. I have Access 2013 at home, but my office uses 2007. It only happens on forms in 2007.

  • 5. AZ Dave  |  January 15th, 2014 at 1:58 am

    Whoops! I mistakenly tried to enter 2 email addresses. The only additional observation is that I do not get the error if the form is unbound. I would hate to have to remove all the messages and return to xmsgbox.

  • 6. Renaud Bompuis  |  February 3rd, 2014 at 11:24 am

    @David Walsh: as you noticed, this is an issue due to the un-escaping of the strings so they can display Unicode. If the message contains paths, the \ could be misinterpreted as the start of an escape sequence.
    I have tried to mitigate this in today’s update to v1.9, but the only way to get rid of the issue completely would be to either escape all backslashses as \\ or use EscStr() from my other library on the path before inserting it in your message so that it is properly escaped before being un-escaped again by the messagebox.

  • 7. Renaud Bompuis  |  February 3rd, 2014 at 11:30 am

    @Mark Singer: The issue is that it’s almost impossible to get the real size of HTML text before it is rendered, so we don’t exactly know how much space a given string is going to take when you change the size of the text.
    I try to get some pragmatic defaults in the code, but if you change the text size too much it’s probably going to display wrong.

    You will either need to try to format your text so it fits correctly, or change some of the code to suit your usage.

  • 8. AZ Dave  |  February 6th, 2014 at 1:21 am

    I have reviewed the Dialog Form, the module, reloaded both from V1.8 and examined every use of Dialog. Box. In desperation, I even replaced all the “\n’s wit vbcrlf and still have the error: “NAMEDATABASE cannot follow hyperlink to ’000000′ Please verify destination”. It only occurs when a form is opened. After I click the “:OK” on the error message all other messages are displayed without the error. Any suggestions would be appreciated. I truly appreciate the functionality and would hate having to revert to xmsgbox.



  • 9. AZ Dave  |  February 6th, 2014 at 6:32 am

    I saw the update and loaded v1.9 (module and form). Still get the error. I have another database I wrote for another department, so I replaced all the Msgbox with Dialog. Box (added new form and module). Works great, no error. Now I am confused. Could it be something in one of the libraries or a missing Reference? However, both databases have the same references.

  • 10. David Dewick  |  March 13th, 2014 at 6:54 pm

    Nice work, and just what I was looking for. I’ve a small suggestion, though.

    I often use message boxes to confirm completion of a user action. The messages are shown, or not, depending on the state of a specific flag. It would be very useful to be able to alter this flag by having a “Do not display this message in future” tick box on the message. Not sure how you’d code it tho’ :(

  • 11. David Dewick  |  March 13th, 2014 at 9:56 pm

    Just another thought …

    Would it be possible to put the caption in the form’s header, also allowing the same kind of formatting that’s available for the message, and then replace the Dialog border with None?

  • 12. Michael  |  May 10th, 2014 at 4:08 pm

    You’ve created an excellent dialog box replacement, and the installation into an existing database is a snap. I, among many others, am very appreciative of the hard work you’ve put into this. Thank you!

  • 13. Fred  |  June 17th, 2014 at 9:47 pm

    Hi Renaud,

    Good to see you are still updating this very useful utility, thank you. One issue I ran into after updating: If I have dialogs with custom buttons, this causes an error with invalid parameters.

    To resolve this I did the following: In the Dialog module I moved the two new parameters (AllowCopyToClipboard & AllowSaveToFile) in both Box and RichBox function declarations to the end of the parameter list. This stopped the error and all now works again.

    I also added = False to both to make it default to not shown unless I wanted them to, but that is personal preference!

    Hope this helps anyone having a similar issue

    Regards, Fred

  • 14. Bill C  |  July 9th, 2014 at 3:51 am

    Nice Job! Could one of the “modifications I could make myself” be to determine the screen coordinates that I’d like the box to be placed at? Regular ole MsgBox seems to always CENTER the box, which often overlays important info BEHIND it.

  • 15. Mark Singer  |  October 10th, 2014 at 3:11 am

    Hi Renaud,

    Referring to posts 103 & 106. I had a similar issue as David Walsh with respect to properly displaying the \ character. I’m trying to display a folder & file path string.
    I could not get the escaping of all backslashes to work. I could not find a function called EscStr() in StringUtils.bas.
    I did find another version of UnEscStr() that was slightly different from the one used by I presume that the reference to EscStr() was a typo. I loaded StringUtils.bas into my DB but that version of UnEscStr() did not work either.

    I ended up doing something similar to what David Walsh did. I added an additional parameter to Box():

        Optional ByVal boolEscape As Variant = False

    I changed the f.Prompt line to:

        If boolEscape = True Then
            f.Prompt = UnEscStr(Prompt, toHtml:=False)
            f.Prompt = Prompt
        End If

    This way I am able to preserve the functionality of UnEscStr() in Box() when I want it and disable it when don’t want it. I chose to default it to False as I tend to use Unicode minimally.

    Would there be a way for the next version to handle backslashes (“\”) properly?



  • 16. Matthias Kläy  |  October 16th, 2014 at 2:52 am

    This is great work. However, I found a snag with the SaveToFile function. In the following code,

        Dim strFile As String
        strFile = Dir$("C:\Temp\*.")
        Do While strFile <> vbNullString
           Call Dialog.Box("Test")
           strFile = Dir$

    using the SaveToFile button in the MsgBox will by itself call Dir("...") in the function FileExist. This results in a run-time error 5 “Invalid procedure call or argument” on the next line, strFile = Dir$.

    This is very hard to debug. I propose to replace the Dir function with a call to the FindFirstFileW API function (note the “W” at the end, for Unicode support).

    With kind regards
    Matthias Kläy,

  • 17. Renaud Bompuis  |  October 21st, 2014 at 11:38 pm

    Version 1.10 is out, see the list of changes for details.

    @ Matthias Kläy: I have modified the FileExist() function to correct the issue you reported.

    @Mark Singer: the new NoStrEsc option and its global default Dialog.DefaultNoStrEsc should do what you wanted, although for adding paths to a message, I recommend using the helper function dialog.EscBackslash().

    @Fred: apologies for that issue, I inserted the new options in the middle of the existing ones, which would cause problems if you were not using the named parameters. All future options will be added to the end of the list of parameters to avoid this from now on.

    @Bill C: I thought a bit about that but decided against it for now. I’m afraid it may startle the user to have the box show in unusual locations. If I can find an elegant way to make this work, I might implement it.

    @Michael: thank you for taking the time to let me know you like this small utility!

    @David Dewick: thanks for finally pushing me to implement the ‘do not display this box again.!

  • 18. Matthias Kläy  |  October 28th, 2014 at 10:18 am

    Hi Renaud

    Thank you for the new release! I like the use of the GetFileAttributes function in order to check if a file exists.

    I have a couple of remarks.

    First, if one diplays a VBA MsgBox while the hourglass is turned on, the cursor will turn into the normal arrow shape as soon as you move the mouse over the MsgBox window. It returns to the hourglass shape when you move out of the window again. In your Dialog.Box the cursor shape does not change. This may confuse users because they have to click on a button while the hourglass is on. I propose the following modification:

    In the declarations section of the FormDialog module, add

        Private Type Point
            x As Long
            y As Long
        End Type
        Private Declare Function GetCursorPos Lib "user32" (lpPoint As Point) As Long

    Change the definition of Sub Redimension to

        Private Function Redimension() As RECT

    At the end of function Redimenson, just after the call to SetWindowPos, add the lines

         Redimension.Left = screenX
         Redimension.Right = screenX + formWidth
         Redimension.Top = screenY
         Redimension.Bottom = screenY + formHeight

    In the function ShowModal, make the following changes

        ' Calulate the proper dimensions of the textbox and the form
        Dim r As RECT
        r = Redimension

    and modify the waiting loop to

        Dim OldShape As Integer
        OldShape = Screen.MousePointer
        Do While m_Result = -1
            If GetCursorPos(p) &lt;&gt; 0 Then
               If r.Left &lt;= p.x And p.x &lt;= r.Right And r.Top &lt;= p.y And p.y &lt;= r.Bottom Then
                  Screen.MousePointer = 1
                  Screen.MousePointer = OldShape
              End If
            End If
            Sleep 50

    and finally, at the end of the function, revert to the saved cursor shape:

            Screen.MousePointer = OldShape
            ShowModal = m_Result


    The second remark concerns the Open fname For Binary As #intFile statement in the btCopyToFile_Click event in FrmDialog. This statement cannot handle general Unicode file names (fname with code points outside of the ANSI range).
    To truly pass the Turkey Test (also see the article on the Moserware blog), I recommend to replace the Open statement with the CreateFileW/WriteFileW API functions.

    In fact, none of the VBA file functions ChDir, CurDir, Dir, Kill, Name, Open (and consequently everything that depends on an open file number, i.e. statements Close #, Get #, Input #, Line Input #, Lock #, Print #, Put #, Reset #, Seek #, Unlock #, Width #, Write # and functions EOF, FileAttr, Input, LOF, Loc and Seek), SetAttr, MkDir, RmDir, FileDateTime, FileLen and GetAttr as well as the Help feature in the VBA MsgBox function (!) can handle Unicode file names names properly.
    The notable exceptions are the GetObject/CreateObject and Shell functions.

    This is enough for today ;-)
    Thank you again! I have learned a lot about Unicode and other stuff from your blog.

    Kind regards, Matthias Kläy

  • 19. Renaud Bompuis  |  October 28th, 2014 at 10:58 pm

    @Matthias: thanks a lot for taking the time to make the code better.
    Regarding the mouse cursor, I’ll add this to the next update, it’s a good catch.
    For the filename save, you are also right, VBA’s origins were in a pre-unicode world and most of the internal functions tend to call the ANSI version of the Win32API. I will update that code as well in the next update.

    Thanks again for the feedback and all the work you put into reviewing all this.

    Take care,


  • 20. Mark Singer  |  October 29th, 2014 at 5:15 am

    I’ll switch from 1.9 to 1.10 and make the necessary changes in my code when I have some time to implement and test.

    I did notice that Dialog.Box will not handle vbTab or chr(9) properly. Instead of a standard tab spacing, I get nothing so “xxxx” & vbtab & “yyyy” looks like “xxxxyyyy”. Is this a 1.9 issue or an overall issue? Dialog.Box appears to be using a proportional font vs. a fixed-width font. This throws off any attempt to align simple columns in Dialog.Box. I was hoping to work around this issue by using vbTab. I am trying to avoid coding a separate form.

    Thoughts? Suggestions?

  • 21. MHabibi  |  November 18th, 2014 at 2:44 am

    Hi, An excellent addition to any MS Access project indeed.

    Please could you advise where I went wrong?

        Sub NewLineTest()
        Dialog.Box Prompt:="Line 1- This is a rather long line, just to test how far we can go with this, If your screen is large enough, there should not be any line return in this very long sentence.&#092;n" & _
                           "Line 2- This is a rather long line, just to test how far we can go with this, If your screen is large enough, there should not be any line return in this very long sentence.", _
                    Buttons:=(vbOKOnly), _
                    Title:="Test1", _
        End Sub
  • 22. Renaud Bompuis  |  November 22nd, 2014 at 9:16 pm

    @MHabibi: I would presume that Buttons:=(vbOKOnly) should be Buttons:=vbOKOnly instead.

    If you are still getting an error message, please let me know exactly which one.

  • 23. Matthias Kläy  |  November 22nd, 2014 at 11:07 pm

    @MHabibi: I guess you are wondering why you don’t get a new line in your example. There are three things to look at here:

    1. Using the backslash \ itself or the quoted backslash \
    2. Using Dialog.Box or Dialog.RichBox
    3. The setting of the NoStrEsc progerty. By default, this property is set to True,, meaning that the backslash character \ is taken literally and not interpreted as an escape character.

    The quoted backslash \ can never be used as an escape character to get a new line. Here are the four possible cases:

    Dialog.DefaultNoStrEsc = True Dialog.Box Prompt:="Line 1.\nLine 2." Dialog.RichBox Prompt:="Line 1.\nLine 2." Dialog.DefaultNoStrEsc = False Dialog.Box Prompt:="Line 1.\nLine 2." Dialog.RichBox Prompt:="Line 1.\nLine 2."

    Note that in Dialog.RichBox the quotet backslash is replaced by the actual \-character, while in Dialog.Box it is always shown as \

    To get a line break, you must use \ itself and set NoStrEsc to false.

    Dialog.DefaultNoStrEsc = False Dialog.Box Prompt:="Line 1.\nLine 2." Dialog.RichBox Prompt:="Line 1.\nLine 2."

    Just to complete all 8 possibilities, if NoStrEsc is set to True, the \-character will not be interpreted as an escape character:

    Dialog.DefaultNoStrEsc = True Dialog.Box Prompt:="Line 1.\nLine 2." Dialog.RichBox Prompt:="Line 1.\nLine 2."

    HTH, Matthias Kläy

  • 24. Hendrik  |  December 4th, 2014 at 4:36 pm

    Hi I have teid to use your code in my access database 2010, Have put this in as to be my messagbox.

    The problem is It does not show on two lines, but on one line. What am I doing wrong here.

    Dialog.RichBox “This is a bold message.\n” & “Click the button to dismiss.”, vbOKOnly, “RichText Message Title”

  • 25. Hendrik  |  December 4th, 2014 at 4:53 pm

    I am trying to use this, but cannot get it to work with new line

    Dialog.RichBox “Tape # : ” & Me.Tape \ n & “Sticker # : ” & Me.Container1 & vbCrLf & “Book # : ” & Me.Book & vbCrLf & “Date send Out :” & Me.DateSendOut, , “Saving………….”

  • 26. Hendrik  |  December 8th, 2014 at 7:18 pm

    Can you please help me with this, when I even run this in my form in access 2010, it does not give me a new line, how can I get itv to work.

    Private Sub Save_Click() 'Dialog.RichBox "This is a bold message.\n" & "Click the button to dismiss.", vbOKOnly, "RichText Message Title" end sub

  • 27. Piper  |  December 22nd, 2014 at 7:02 pm

    It is working very well

  • 28. Matthias Kläy  |  February 3rd, 2015 at 10:08 pm

    Hi Renaud

    In very rare cases I get an error 2100 “The control or subform control is too large for this location” on the line

    txtMessage.Height = boxHeight

    in the function Redimension.

    Now I know that the text to be displayed is very short, e.g. “The document has been imported” (no Rich text is involved). I cannot really force this error to appear, but the error 2100 can also occur if the boxHeight is negative.

    A negative boxHeight can happen if the call

    hMonitor = MonitorFromWindow(ParenthWnd, &H0)

    returns 0 in hMonitor. The subsequent call to GetMonitorInfo will result in monitorWidth and monitorHeight both being 0, resulting in a negative boxHeight value further down.

    I suspect ths can happen in some situations where a long running process in Access is started, and the user switches away from Access before the process is finished and has displayed the message box.

    I propose to change the call to MonitorFromWindow to

    hMonitor = MonitorFromWindow(ParenthWnd, &H1)

    This will return the handle to the primary monitor if the actual monitor cannot be determined. Possible values for the dwFlags argument of MonitorFromVindow are


    see The constants are defined in WinUser.h

    Kind regards Matthias Kläy

  • 29. GreekGuy  |  February 9th, 2015 at 8:05 pm

    Proposal: How about a ‘print’ option?

    Great great work, great tool. U r amazing as it is. Just a thought.

  • 30. Dave Holbon  |  February 22nd, 2015 at 10:26 pm

    Wonderful work must have taken ages to implement this. Using it throughout my new application.

    One small observation: – I download the latest version last week and whilst there’s an event for button 3 in the code on the dialog box, its not associated with the button, at least in my version.

    Maybe some corruption occurred at some stage. Easily fixed though.

  • 31. John  |  February 24th, 2015 at 4:16 pm

    This looks great – exactly what I’m looking for. I’d like to use/adapt it for Excel. I don’t have Access 2007+ (other than runtime) available, so I cannot simply export the code.

    So, would you be willing to post for download, or perhaps email, the VBA modules as text files?


  • 32. Mohamed  |  March 12th, 2015 at 9:33 pm

    @Matthias Kläy:

    Thank You Kindly for explaining this. Your explanations have helped get this excellent feature working properly in my project.

    Kindest Regards, Mohamed

  • 33. Roger  |  March 17th, 2015 at 7:14 pm

    Thank you soo much for creating this, was exactly what I was looking for! Finaly my messageboxes look the way I want them to :D

    +1 for the proposal by @GreekGuy A print button would be awesome!

  • 34. Patrick Geiser  |  April 8th, 2015 at 11:19 pm


    I wanted to make a comment on Matthias Kläy’s post (n. 118). His modifications regarding the cursor are great and it’s just what was missing.

    But what if you move the DialogBox around the screen ? The window’s position will not be updated as it is stored in variable `r`, at the moment the dialog is displayed.

    I would suggest to add the following code in the `ShowModal` Function, in the while-loop at the end. It will look like this:

        Do While m_Result = -1
        GetWindowRect Me.hwnd, r
        If GetCursorPos(p) <> 0 Then
           If r.Left <= p.X And p.X <= r.Right And r.Top <= p.Y And p.Y <= r.Bottom Then
              Screen.MousePointer = 1
              Screen.MousePointer = oldShape
          End If
        End If
        Sleep 50

    The modifications made in the “Redimension” Sub are no longer needed.

    Regards, Patrick

  • 35. Matthias Kläy  |  April 21st, 2015 at 10:14 pm

    @Patrick: Good point, thank you! Only I think that GetWindowRect is not declared, so one has to add

    If VBA7 Then

    Private Declare Function GetWindowRect Lib "user32" (ByVal hwnd As LongPtr, lpRect As RECT) As Long<br>


    Private Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long<br>

    End If

    in the declarations section. Matthias Kläy

  • 36. Patrick Geiser  |  April 22nd, 2015 at 8:17 pm

    @Matthias: you’re right. Thank you for adding the declarations. It was in my own Access libraries, that’s why I forgot to mention.


  • 37. RW Crouch  |  May 5th, 2015 at 11:05 pm

    I am using your enhanced message box in the Report_NoData event on my reports. If the user previews a report and there is no data, they are able to answer the no data prompt without issue. However, if they try to print it directly, the MS Access “Now Printing” dialog comes up along with the no data prompt. Neither prompt can be answered so the user must crash out of the program. How should I use the enhanced message box in this situation so the user can answer the no data prompt?

  • 38. Matthias Kläy  |  May 11th, 2015 at 10:02 pm

    @RW Crouch: I can confirm this issue. I have two workarounds: First, use the standard MsgBox in this situation (!). Second, show the Dialog.Box only after the report is closed:

    In a standard module, declare a public variable

    Public ReportNoData As Boolean

    In the reoprts NoData event, set the variable to True:

    Private Sub Report_NoData(Cancel As Integer) ReportNoData = True Cancel = True End Sub

    Then open the report like this

    Dim ErrNr As Long

    ReportNoData = False On Error Resume Next DoCmd.OpenReport "MyReport", acViewNormal ErrNr = Err.Number On Error GoTo 0 If ErrNr = 2501 And ReportNoData Then Call Dialog.Box("Nothing to print", vbOKOnly, "MyReport") ReportNoData = False End If

    There are some ways to minimize or hide the “Now Printing” dialog, see, e.g., . However, this does not help.

    Perhaps there is a way to “steal” the focus from the “Now Printing” dialog, but this is beyond my capabilities. But since the MsgBox can do it, it should be possible!

  • 39. Dusan Markovic  |  June 3rd, 2015 at 7:35 pm

    Is it possible to show the enhanced message box or rich box modeless way, so that the user could continue working on calling from?

  • 40. RW Crouch  |  June 10th, 2015 at 4:25 am

    @Matthias Klay: I was able to come up with a solution using the article you mentioned about using an API call to minimize the “Now Printing” dialog. I added additional code to the Form_Timer event that checks to see if FormDialog is loaded and, if it is, uses the Sleep API function to wait for two seconds and then close FormDialog. Since I print all of my reports from a central form location and all reports have a standardized ReportNoData function, this solution worked better for me that your suggested solution.

  • 41. JimW  |  June 11th, 2015 at 6:12 am

    Thank you very much for this. I downloaded yesterday and it is working great for most of my uses.

    However, there is one area where it is not. From my primary database form I open a form for selecting items to filter on. If I click on the “Apply Filter” command button and no filters have been selected, I use a standard message box to advise that no filter has been selected. When I click on “OK”, the message box closes and I am returned to the filter form.

    I have tried using the RichText form of the enhanced message box instead. It opens fine and looks good. The filter form stays open behind the message box. However, when I click on OK, the enhanced message box is closed and I am returned to the original database form, not the filtering form. What code should I use after clicking OK to return me to the filtering form.

    Thank you in advance for any advice.

    Jim W

  • 42. JimW  |  June 11th, 2015 at 11:26 pm

    SOLVED! After a good night’s sleep, I realized an error had crept into my original message box routine. For some reason I had the IF – Else with the message box to If-End If, and did not realize I was having the same problem as above and it carried over to my use of the Enhanced Message Box. I just changed the End If to Else, and put the End If in the proper place, and it is working as I want.

    Now on to changing the remainder of my message boxes to the Enhanced Message Box.

    I hope this helps someone else.

    Jim W

  • 43. wayne  |  July 10th, 2015 at 8:42 pm

    How do I close the dialog box programmatically?

  • 44. Sophie  |  July 27th, 2015 at 9:58 pm

    For the Custom button thisis the right code

    dr = Dialog.Box(Prompt:=”This is a custom button label test”, _ Buttons:=(vbCustom + vbInformation), _ Title:=”A custom message”, _ LabelButton1:=”Hit Button 1!”, _ LabelButton2:=”No!, Me! Me!”, _ LabelButton3:=”Forget it!”)

  • 45. David Erwin  |  October 10th, 2015 at 1:03 am

    I just updated to your latest version that includes the “DismissID” capability. It truly is a great enhancement to the standard MS MsgBox. However, I have a peculiar situation in that now all my Dialog.Box and Dialog.RichBox ignore “\n” I tried replacing with vbcrlf and this is also ignored.

  • 46. Daniel  |  October 24th, 2015 at 2:37 am

    Beautiful utility and by far superior to what is natively possible in VBA. Very nice and thank you for sharing. I will be adding a link to your site from my blog.

  • 47. Johnh  |  November 18th, 2015 at 1:20 am

    Anyone having trouble with managing escaped characters after ‘upgrading’ to Office 2013? Library issues?

  • 48. V S Rawat  |  December 6th, 2015 at 11:01 pm

    I want unicode support for Hindi Devangari in vba macros MsgBox in MS WORD 2010.

    As this code is for ACCESS, would it run on WORD also?

    If not, could you please share a MS WORD version of the same?


    Rawat India

  • 49. Phil Stabton  |  January 29th, 2016 at 10:22 pm

    Intrigued to know why I can’t highlight portions of the message to copy and paste them. Could be quite useful when you want to “Google” error messages.


  • 50. Phil Stanton  |  January 29th, 2016 at 11:06 pm

    Sorry, solved the problem. If you txtMessage Enabled to True and in Module Dialog Function Box and Function RichBox add the following 2 lines marked by the #######

    ' Make it visible and wait forthe user until we get the result
    f.SetFocus      '###############
    f.txtMessage.SetFocus   '#############
    RichBox = f.ShowModal()

    the box becomes “live” and bits can be copied and hyperlinks work.

    Can anyone spot a problem?


Leave a Comment

(Will not be shown)

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Renaud This is a simple technical weblog where I dump thoughts and experiences from my computer-related world.
It is mostly focused on software development but I also have wider interests and dabble in architecture, business and system administration.
More About me…

My StackOverflow Profile
My (sporadically active) StackOVerflow account

Most Recent Posts