I am working and excel addin and I am under the need to open a new window of the same workbook to enter data in a different worksheet. For the new window, I will need to know when the window is being closed so I can do some validations on the data entered. Is there a way to know when a Workbook window is being closed?
Thanks.
Take a look at this document:
http://support.microsoft.com/kb/213566
Create a Module and a Class Module. Code is below.
Class Module code:
Public WithEvents appevent As Application
Dim windowsCount As Integer
Private Sub appevent_WindowActivate(ByVal Wb As Workbook, ByVal Wn As Window)
If windowsCount <> Application.Windows.Count Then
MsgBox "You closed a window"
End If
End Sub
Private Sub appevent_WindowDeactivate(ByVal Wb As Workbook, ByVal Wn As Window)
windowsCount = Application.Windows.Count
End Sub
Module Code:
Dim myobject As New Class1
Sub Test()
Set myobject.appevent = Application
End Sub
And this handler for the workbook:
Private Sub Workbook_Open()
Test
End Sub
You can handle the BeforeClose event. An example using VBA is available here.
Related
I want to create class that is intended to serve as configuration management and serving helper. It would store some basic connection settings in XML file, read it to it's own properties and serve to any other module, form, object etc.
I've created a class like following:
Option Compare Database
Option Explicit
Private mstrSqlServerName As String
'...
Public Property Get SqlServerName() As String
SqlServerName = mstrSqlServerName
End Property
'...
Private Sub Class_Initialize()
readConfigFile
End Sub
Private Function loadConfigFile() As MSXML2.DOMDocument60
On Error GoTo FunctionError
Dim XMLFileName As String
Dim objRoot As IXMLDOMElement
Dim strMsg As String
Dim oXMLFile As MSXML2.DOMDocument60
'Open the xml file
Set oXMLFile = New MSXML2.DOMDocument60
XMLFileName = (Application.CurrentProject.Path & "\config.xml")
With oXMLFile
.validateOnParse = True
.SetProperty "SelectionLanguage", "XPath"
.async = False
.Load (XMLFileName)
End With
Set loadConfigFile = oXMLFile
End Function
Public Sub readConfigFile()
Dim oXMLFile As MSXML2.DOMDocument60
Set oXMLFile = loadConfigFile
mstrSqlServerName = oXMLFile.selectSingleNode("//config/database/SqlServerName").Text
End Sub
I've tested my class in intermediate window and everything works flawlessly. Then
I've created hidden form to instantiate the class like follows:
'frmYouShouldNotSeeMe
Option Compare Database
Option Explicit
Public configuration As clsConfiguration
Private Sub Form_Load()
Set configuration = New clsConfiguration
MsgBox Prompt:=configuration.SqlServerName
End Sub
Now, from other module/form/report etc. i wanted to call configuration item with:
MsgBox configuration.SqlServerName
But when I'm trying to compile my project it says "compile error, variable not defined". In short: I cannot find a way to use instantiated (named) object properties from other objects of database. They just don't know anything about it's existence. In the intermediate window everything works, I can instantiate object and call GET functions. What did I do wrong? Probably it's just what OOP design brings and I just don't understand that. What is the best way to achieve this goal?
You can add two public functions to your class.
Like this:
Public Function SqlServerName() As String
SqlServerName = oXMLFile.SelectSingleNode("//config/database/SqlServerName").Text
End Function
Public Function GetConfig(strNode As String, strValue As String) As String
Dim strXPATH As String
strXMPATH = "//config/" & strNode & "/" & strValue
GetConfig = oXMLFile.SelectSingleNode(strXMPATH).Text
End Function
Now in code you can use:
Msgbox configuration.SqlServerName
Or to get any config you can use the helper functon with 2 params
Msgbox configuration("database","SqlServerName")
So, the public members of the class HAVE to be written by you. It does not by "magic" or out of the blue expose information from that class. You can use public functions, and they will appear as inteli-sense when you create such public functions. (they become properties of the class). So, your syntax does not work because you don't have a public function (or a property get) that exposes what you want. You can use a property let/get, but a public function also works very well as the above shows.
So, either make a public function for each "thing" (node) you want to expose, or use the helper function above, and you can pass the key + node value with the function that accepts 2 parameters. Both the above will become part of the class, show inteli-sense during coding - you are free to add more public members to the class as per above.
#Edit
the sample code shows this:
Set configuration = New clsConfiguration
MsgBox Prompt:=configuration.SqlServerName
it needs to be this:
dim configuration as New clsConfiuration
MsgBox Prompt:=configuration.SqlServerName
You could on application startup setup a GLOBAL var called configueration, and thus not have to declare the configeration variable in the forms code.
You thus need a global var - set it up in your startup code before any form is launched.
So in a standard code module, you need this:
Public configuration as new clsConfiguration
But, your screen shot of the code is MISSING the create of the configuartion variable.
And your provided code has this:
Set configuration = New clsConfiguration
MsgBox Prompt:=configuration.SqlServerName
So where and when did you define configuration as global scoped variable?
You either have to use LOCAL scope to the form (in fact your on-load event)
dim configuration as New clsConfiuration
MsgBox Prompt:=configuration.SqlServerName
Or, you can as noted, declare "configuration" as a public global varible in a starndard code module (not forms module, and of course not a class module).
if you use the "new" keyword, then you can use this:
Public configuration as New clsConfiuration
The above can be placed in any standard code module - it will be global in scope.
With above, then in the forms load event, this will work:
MsgBox Prompt:=configuration.SqlServerName
As configuration is declared in frmYouShouldNotSeeMe you can refer to the form to access the variable, as long as the form is open.
Debug.Print Forms("frmYouShouldNotSeeMe").configuration.SqlServerName
I tried this in an Access newgroup, and got over a hundred views, but not a single response, so I hope it fares better here.
I'm trying to get a grip on custom events in VBA. I've scoured endless sources on the net, studied my manuals, experimented with everything I can think of, and success is still somewhat tenuous.
Exactly what I hope to accomplish is not all that complicated, and seems like it should be ideal for custom event routines. I have main forms with comboboxes and listboxes fed from tables or queries. The user can open various dialog boxes and do things to modify the tables. When that activity is done, I would like to requery the box(es) affected by any such activity. The way I have done it in the past was to set a global 'SourceHasChanged' Boolean variable and check its status upon returning from the dialog. It works, but is a bit unwieldy, so I decided to try replacing this with custom events.
Hours of studying and endless dead-end tries and repeats have finally produced the following bits of code. They do nothing spectacular. There is a table called T. The dialog form adds records on each click of the Add button. The main form has another button that deletes all but the first record in the table. Each set of code is supposed to fire an event indicating that the listbox is to be requeried. The code in the main form does okay, but the code in the dialog refuses to activate the StalaSeZmena event. Obviously (I think, anyway), that's because the dialog from creates a new instance of the class module. But I have to have a WithEvents variable in the dialog form. If I don't, I would have to make a reference to the WithEvents variable in the main form. Requiring forms to know that much about each other is exactly back-asswards from what I thought the custom event route was going to accomplish. It would be easier and less confusing to just stay with a global status variable.
Class Module [Zmena]
Public WithEvents Udalost As HlaseniZmeny
Private Sub Udalost_StalaSeZmena()
Form_Mane.lstS.Requery
Debug.Print "Requery via class module"
End Sub
Class Module [HlaseniZmeny]
Public Event StalaSeZmena()
Public Sub OhlasitZmenu()
RaiseEvent StalaSeZmena
End Sub
Regular Module
Public chg As Zmena
Form Code [Mane]
Private WithEvents chgMane As HlaseniZmeny
Private Sub cmdCallDialog_Click()
DoCmd.OpenForm "Dia", acNormal, , , , acDialog
End Sub
Private Sub cmdShrinkT_Click()
CurrentDb.Execute "Delete * From T Where Pole1 <> 'A'"
chgMane.OhlasitZmenu
End Sub
Private Sub Form_Open(Cancel As Integer)
Me.Label1.Caption = Me.SpinButton1.Value
Set chg = New Zmena
Set chgMane = New HlaseniZmeny
Set chg.Udalost = chgMane
End Sub
Private Sub chgMane_StalaSeZmena()
lstS.Requery
Debug.Print "Requery from event on main"
End Sub
Form Code [Dia]
Private WithEvents chgDia As HlaseniZmeny
Private Sub cmdAdd_Click()
CurrentDb.Execute "Insert Into T (Pole1) Values(chr(asc('" & DMax("Pole1", "T", "Pole1") & "')+1))"
Set chgDia = New HlaseniZmeny
Set chg.Udalost = chgDia
chgDia.OhlasitZmenu
Set chgDia = Nothing
End Sub
It's functional, but feels awkward, clunky and not at all intuitive, like scratching my left ear with my right foot. The class module has a reference to the main form, which violates the principle of encapsulation, but I found no way to make the dialog form activate the event routine in the main form. I have to have a global variable to link the two WithEvents variables to, or nothing works, but this also violates encapsulation.
Is this really how these constructs are supposed to operate, or have I accidentally stumbled onto a Mad-Max version that happens to work, but isn't the proper way to build such procedures?
I am trying to create an appointment/meeting notice template that prevents forwarding, defaults to no response required and is sent from a delegated/shared calendar. I have the script to change the response required and can disable the forwarding option in the actions, but I can't figure out the delegate. I've found the getname script:
Sub ResolveName()
Dim myNamespace As Outlook.NameSpace
Dim myRecipient As Outlook.Recipient
Dim CalendarFolder As Outlook.Folder
Set myNamespace = Application.GetNamespace("MAPI")
Set myRecipient = myNamespace.CreateRecipient("Larry M Garrett")
myRecipient.Resolve
If myRecipient.Resolved Then
Call ShowCalendar(myNamespace, myRecipient)
End If
End Sub
Sub ShowCalendar(myNamespace, myRecipient)
Dim CalendarFolder As Outlook.Folder
Set CalendarFolder = _
myNamespace.GetSharedDefaultFolder _
(myRecipient, olFolderCalendar)
CalendarFolder.Display
End Sub
This works in visual basic, but it only opens the shared calendar. It doesn't set the appointment to come from the shared calendar. I get a code error if i put it into the "view code" section and try to run the form. I feel like i'm missing the step where i tell it to send from the delegated calendar but i can't find it. Thanks.
It looks like you need to use the shared calendar folder to create an appointment item. Use the sharedCalendarFolder.Items.Add method to create an appointment.
If I open a .mhtml file in word, and click the "Save As" option, the default "Save As Type" is .mhtml. But I need the default "Save As Type" to be .doc/.docx. Is there any way to achieve this?
Create handler for saving event, in this event analyse type of the original document and show your own SaveAs dialog.
Details:
1. Handler
In normal template, create a class, for example clsSaveAs:
Public WithEvents appWord As Word.Application
Private Function IsMime(fileName As String)
Dim mimeTag As String
'open document
Open fileName For Input Access Read As #1
On Error Resume Next
'read beginning of the document
Input #1, mimeTag
On Error GoTo 0
Close #1
'MHTM file starts with "MIME" string
IsMime = Left(mimeTag, 4) = "MIME"
End Function
Private Sub appWord_DocumentBeforeSave _
(ByVal Doc As Document, _
SaveAsUI As Boolean, _
Cancel As Boolean)
'get extension
ar = Split(Doc.Name, ".")
ext = LCase(ar(UBound(ar)))
'what is the document MIME type?
If IsMime(Doc.FullName) Then
'my own saveas dialog
With Application.Dialogs(wdDialogFileSaveAs)
.Format = WdSaveFormat.wdFormatXMLDocument 'docx
.Show
End With
Cancel = True 'cancel saving process
Else
'normal saving
Cancel = False
End If
End Sub
2. Using handler
In normal template create a new module:
Dim csa As New clsSaveAs
Sub Register_Event_Save_As_Handler()
Set csa.appWord = Word.Application
End Sub
'autorun for any opening document
'Note: AutoOpen could be only one in normal template
Sub AutoOpen()
'could be run only for mht, mhtm documents, but never mind
Register_Event_Save_As_Handler
End Sub
You need have this code in the MHTML document. You could do it this way (but I haven't tried it):
create a new document in MS Word and save it as normal HTML file
create in this document a new class (clsSaveAs, see above) and in any module the second part of the code
see at saved document: there is a folder named _files and in this folder a file editdata.mso; this is the macro; you have to code it in a MHTML file (when you save it as MHTML file, you will see, how it is done)
in document you have to link this file, look in HTML document and find a row like
Note that all this job is non-standard and you are walking on thin ice, be careful.
Useful links:
Using Events with the Application Object
Application.DocumentBeforeSave Event
Quoting Office's help documents:
1-Click the File tab.
2-Click Options.
3-Click Save.
4-Under Save documents, click "Word 97-2003 Document (*.doc)" or "Word Document (*.docx)" in the Save files in this format.
I wrote an VBA:
Sub ToChange()
Dim olApp As Outlook.Application
Dim objNachrich As MailItem
Set olApp = New Outlook.Application
Set objNachrich = olApp.CreateItem(0)
Set Mail = objNachrich
Mail.SentOnBehalfOfName = "Info"
Mail.Display
End Sub
It changes the "from"-attribute to "Info" and works fine if I start it.
But, I want to run it automaticly if I open a window to write a new e-mail. Is there a posibility?
Well,
you can add a new button on the menu-bar ;)
If I'm understanding it properly, you can just call this procedure on the Load event of a form.