I have a Word which is used for form filling. The users are filling what is asked and some macros runs depending on what they chose or where they click. This works fine.
I recently decided to make a newer version which countains some ComboBox that are filled when the document is opened. To do that, I used the Document_Open() event.
Now here is the part I don't get : On my side, every time I do open the document, the event is triggered and the ComboBox that should get filled are filled. The problem is, so far I asked some people to test it on their own computer with their Word. Both of them came back to me saying that the ComboBox weren't filled when the document was openned.
To be more specific let's go in the code itself :
In ThisDocument, I have multiple subs that works perfectly fine and this Document_Open() event which gives me trouble.
Private Sub Document_Open()
Application.Run ("Fill.ComboBox")
End Sub
Here, Fill is the name of the Module which contains :
Sub ComboBox()
'Calling another Sub in this Module which adds the Items in the ComboBoxes
'from what parameters it is given
End Sub
Now that this has been stated, why would it work on my side but not work when another user tries it from their computer ?
Miscorsoft Word Versions :
I myself use Microsoft Office Profesionnal 2013 and so are the two users that tested it. That being said, this is intended to be working on any Word liscense from 2007 up to the current versions.
You can try in a module in your document:
Public Sub AutoOpen()
ComboBox
End Sub
I just used this in a Word 2016 document to automagically run a macro.
For documentation: https://support.microsoft.com/en-us/help/286310/description-of-behaviors-of-autoexec-and-autoopen-macros-in-word
Related
I have a .docm file with a Document_Open-sub, which calls another sub to open a small userform - or it's supposed to trigger and open - but it doesn't...
If I make changes to the document and save it - it still doesn't work.
If I make insignificant changes to the VBA-code in the same document (like adding a space character outside a sub) and save it - it suddenly works.
Why does it not work all the time? - and what can I change to make it work?
Additional info (I have no idea if some of it might be relevant)
In most cases the document is downloaded from an internal website and saved locally.
The document we've tested with is saved locally in a location which is trusted in Word.
In cases - where the sub isn't triggered automatically - the sub can be run with ALT+F8 (but that's not what I want).
The functionality works for some user - and not for others.
The functionality in the Document_Open-sub depends on a value read in CustomDocumentProperties.
System: Win10 - Word MSO365 build 2110
Edit - code added:
Public Sub Subrutine1()
ThisDocument.CustomDocumentProperties("prop1").Value = " " 'resetting prop1
UserForm1.Show 'prop1 is set from the userform
End Sub
Private Sub Document_Open()
If ThisDocument.CustomDocumentProperties("prop1").Value = " " Then
Call Subrutine1
End If
End Sub
You could rename your Sub "Subrutine1" to "AutoOpen."
I would recommend the following code.
Private Sub AutoOpen()
Dim myForm As UserForm1
Set myForm = New UserForm1
myForm.Show
Unload myForm
Set myForm = Nothing
End Sub
I would suggest resetting the document property as part of your userform initialization unless you sometimes use it without resetting that.
I would suggest using a document variable rather than a document property.
I suspect you would be better served with a document template rather than a document. In that case, the macro would be named "AutoNew."
I work with 2 different keyboard layouts (qwerty and azerty), and am constantly switching between the two using Alt-Shift. Sometimes when I reach for Ctrl-Z to undo, I get instead Ctrl-W which closes the document. Generally speaking I would in these situations get a Save Prompt, which would alert me to my mistake. However, I am now using OneDrive, with Autosave on the documents I'm working on. As a result, there is never this save prompt. The document is instantly closed and, worse, the undo that I was trying to effect is no longer present when the document is re-opened.
I would like to use VBA attached to the Normal Template, such that, on closing any document created with the VBA template, I will check to see if Autosave is turned on, and if it is, confirm before closing with a messagebox.
Obviously if the user doesn't confirm (e.g. chooses Cancel) then the document should not be closed.
Initially I put my code on Document_Close, but soon realised that here it's too late to Cancel the close. This is no good to me.
Then, based on some online code, I put my code in a class module (EventClassModule). In the ThisDocument module, I initiate the class, and activate the event handler.
My code doesn't ever seem to run, or in anycase, breakpoints don't kick in.
I'm a little unsure of where Normal stops and my normal document begins...
In ThisDocument of Normal Template, I have this VBA
Dim X As New EventClassModule
Sub Register_Event_Handler()
Set X.App = Word.Application
End Sub
Private Sub Document_Open()
Register_Event_Handler
End Sub
And I have a class module called EventClassModule with the following
Public WithEvents App As Word.Application
Private Sub App_DocumentBeforeClose(ByVal Doc As Document, Cancel As Boolean)
Dim res As VbMsgBoxResult
If Me.AutoSaveOn Then
res = MsgBox("OK to Confirm", vbOKCancel, "Closing Document")
If res = vbCancel Then
Cancel = True
End If
End If
End Sub
I would like a prompt to confirm saving, any time a document is closed and the autosave option is turned off.
The Document_Open event handler will only fire if the Normal template is opened via File | Open. To get code to respond when starting Word you need to use an AutoExec routine. Simply rename your routine as below. You can find further info on Auto macros here
Public Sub AutoExec()
Register_Event_Handler
End Sub
Here is an easy way, include a method like this:
Public Sub DocClose()
' Disables Ctrl + W (but not other close methods, e.g. Alt + F4, menus, [X])
' Your code here:
ActiveDocument.Close
End Sub
Basically there are some method names that are used internally by MS-Word, and if you include them in your code they will prevent the default action. If you leave the sub empty it will effectively disable Ctrl + W.
See here for more information: Reserved method names in MS Word VBA
Advantage 1 of this technique
If you use Public WithEvents App As Word.Application and your project gets reset for any reason, and fails to restart... App will be Nothing and none of the events will fire.
Advantage 2 of this technique
On the occasions that you actually want to close a document... with this technique you wont get bugged by a (soon to become) annoying confirmation message - just sayin ;-)
I currently use word templates in my business to help create customer mailings. There's a existing userform coding on our templates that insert the proper return address, phone number, legal entity, etc... onto the letter. Lately we've been having issues with a subset of users (seemingly random, we've been through exhaustive testing and cant find rhyme/reason) who do not receive the popup to choose whatever items they need when they enable macros. In testing we've found that the users have been able to go into vbasic and run the userform manually. I'd like to build in a hotkey option to initialize the userform, please help! Currently, the ThisDocument object has this code to run the userform:
Private Sub Document_New()
Channel_Select.Show
End Sub
From what I've been able to find online, something like the OnKey Command from excel could be used, but I cant find the Word version. Does anyone have experience in this?
I found the answer on a thread about keybinding, but I can't refind that thread. I added 2 new modules to my document, module1 has:
Option Explicit
Sub AddKeyBinding()
With Application
' \\ Do customization in THIS document
.CustomizationContext = ThisDocument
' \\ Add keybinding to this document Shorcut: Alt+r
.KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyAlt, wdKeyR), _
KeyCategory:=wdKeyCategoryCommand, _
Command:="TestKeybinding"
End With
End Sub
Module 2
Option Explicit
' \\ Test sub for keybinding
Sub TestKeybinding()
Channel_Select.Show
End Sub
Run the AddKeyBinding macro, then alt+r will launch the userform on the document
I created my own Outlook form to use it as standard surface to enter certain orders instead of the normal message form. The creation, editing and sending works perfectly fine and in the next step I want to insert some code via VBA.
My problem is that I can´t access the objects of my form in the VBA editor. E.g. I want to show a message box when a certain checkbox is checked. According code would be:
Sub example()
If CheckBox1.Value = True Then
MsgBox("Checkbox 1 is checked.")
End If
End Sub
When I run the code I get the error that the object could not be found. The same goes for every other object, like textboxes or labels etc.
I guess the solution is pretty simple, like putting Item. or sth. like that in front of each object. But so far I wasn't able to find the solution.
I´m using Outlook 2010.
I know this is a year too late but you'll want to do something like this example below. It's kinda a work around but you can get whatever value was selected.
Sub ComboBox1_Click()
Set objPage = Item.GetInspector.ModifiedFormPages("Message")
Set Control = objPage.Controls("ComboBox1")
MsgBox "The value in the " & Control.Name & _
"control has changed to " & Control.Value & "."
End Sub
You should be able to get the value, just get a handle on the object you want using the Inspector
The following is an excerpt from here
When you use a custom form, Outlook only supports the Click event for
controls. This is a natural choice for buttons but not optimal for
controls like the combo box. You write the code by inserting it into a
form’s VBScript editor. You need to have the Outlook form open in the
Form Designer and click the View Code button found in the Form group
of the Developer tab.
Sub CheckBox1_Click()
msgbox "Hello World"
End Sub
The code page is fairly minimal with no syntax highlighting. I just tried this now and it does work. Dont forget to Publish your form to pick up the new changes.
I know this is almost 6 years late but, in VB and VBA, simply start with the form name. (And if that doesn't work, just keep going up a parent object and you'll get there.) So, your code becomes:
Sub example()
If MYFORMNAME.CheckBox1.Value = True Then
MsgBox("Checkbox 1 is checked.")
End If
End Sub
Of course, after typing "MYFORMNAME." you'll know if it will work because typomatic will kick in when the system recognizes "MYFORMNAME" after you hit the period.
I have a VBA (Excel 2010) system which involves selecting an item from a listbox and then displaying it in another form. Here is a very simplified version of what happens.
' Part of frmForm1 code module
sub lstListbox_Click
dim MyEvent as string
dim i as integer
i=me.lstListbox.listindex
MyEvent=me.lstlistbox.list(i)
' Now show the item in the second form
Load frmForm2
me.hide
ThisWorkbook.LoadDataIntoForm2 (frmForm2, MyEvent)
frmForm2.show
unload frmForm2
me.show
end sub
The listbox accepts the click, and first the event (the event handler is giver above). Key parts of the event handler are:
Load the second form (to display the detail data)
Pass the second form as a UserForm parameter to a procedure (LoadDataIntoForm2)
Hide the host form (frmForm1) and show the second form (frmForm2)
When the second form processes an Exit click, the code looks like this:
' Part of frmForm2 code module
sub cmdExit_Click
me.hide
end sub
The first time round it works fine - but when I return to frmForm1 (in the tail end of the lstListBox_Click procedure), even though the rest of the form is operative, the listbox remains stubbornly unresponsive.
I've managed to abstract this down to a little demo system if that would help - the same behavior is seen there. (It's regular .xls file, but that seems not to be easily acceptable as an upload)
Has anyone seen this before? And does anyone have any ideas how I might get this to work the way I want it to?
Thanks,
Tony
The default for the .Show method is to make the form modal. Explicitly set it to modeless:
Sub lstListbox_Click
...
Me.Show vbModeless
End Sub