How to change the title bar text of a Userform in VBA? - vba

I'm maintaining an old-ish application written in VBA for Excel 2002 (XP)/2003, and am trying to internationalise it.
To do this, I read in the translated strings dynamically and update the various controls on my userform by updating their .Caption property.
This works as expected for all controls but not for the form itself -- when I change the form's .Caption property, then the title bar keeps displaying the "hard-coded" value, and the new value is instead displayed just below it, at the top of the "canvas" of the form itself.
Is it possible to change the title bar text of a UserForm after it has been shown, or do I have to change the .Caption property of the form before it is shown in order for it to be reflected in the title bar rather than in the canvas/client area?
My code looks something like this:
' in frmFoo
Private Sub UserForm_Activate()
' ...
TranslateDialog Me, "frmFoo"
' ...
End Sub
' in a VBA module
Sub TranslateDialog(pForm As UserForm, pFormName As String)
Dim new Caption As String
Const notFound As String = "###!!##NOTFOUND##!!###"
' ...
' GetMessage() returns the translated message for a given key, or the
' default value (second parameter) if no translation is available.
' The translation key for the form caption is the form name itself.
newCaption = GetMessage(pFormName, notFound)
If newCaption <> notFound Then pForm.Caption = newCaption
' ...
End Sub
As I said, the assignment to pForm.Caption does have an effect - but it doesn't write to the title bar of the window, but rather directly beneath it. I'm running Excel 2003 on Windows XP SP 3.

Your frmFoo is not actually the same type as the base UserForm, rather it's internally "descended" from it in VBA's wierd OO implementation so you can't use that reliably as a parameter type, using Object instead will work;
Sub TranslateDialog(pForm As Object, pFormName As String)

Related

Show/Hide FileExplorer in Access Form

I've been trying to use a combobox to show/hide a PDF viewer that I've added into a MS Access form.
When I use the form_current event, then the form only updates when I move between the data entries. When I use the afterupdate event, the same code does nothing at all.
Does anyone have a fix? The code I have used is below, which I have tried both the AfterUpdate event for the Browser and the Form_Current event for the whole form
Private Sub PDFT900_AfterUpdate() / Private Sub Form_Current()
Dim ESNComb As String
ESNComb = Me.ESNCombo.Column(1)
If ESNComb Like "9????" Then
Me.PDFT900.Visible = True
Else
Me.PDFT900.Visible = False
End If
End Sub
In the code below, I'm hiding and showing the Adobe PDF Reader ActiveX control named, "AcroPDF0". Since the Like operator returns true on an expression match and false on a mismatch or no match, it serves as a simple boolean switch for the visible property. I've used the (*) wild card instead of (?). It works {shrug}. See demonstration images below.
Private Sub ESNCombo_AfterUpdate()
'AcroPDF0.Visible = ESNCombo.Text Like "P*"
AcroPDF0.Visible = ESNCombo.Column(0) Like "P*"
AcroPDF0.src = acroPDFOSrc
End Sub
ComboBox List Items
"File Browser" Selected in ComboBox
Toggled ComboBox back to "PDFT900"

Access VBA - How to get the properties of a parent subform, or, get the user-given name for a subform (not the object reference name)

In MS Access 2016, let's say I have 2 forms: frmMain and frmBaby.
I have embedded frmBaby as a subform on frmMain. I have embedded on frmBaby a control (let's say it's a textbox, but it could be any control) named tbxInput.
On frmMain, since frmBaby is a "control" on frmMain, I have given that control the traditional name of subfrmBaby.
Now, in VBA, an event on subfrmBaby passes the tbxInput control ByRef (as Me.tbxInput) to a function that is meant to return the .Left property of the parent of the control passed ByRef. That is, I need the function to determine the .Left property for the location of subfrmBaby on frmMain. (The function is more complicated than this, but for the sake of keeping this question let's just say the function is returning the .Left property value because the .Left value is what I need to perform the function.)
Let's say the function is: Public Function fncLocation(ByRef whtControl As Variant) as Long
(I use Variant so that null values can be passed.)
Here is the code that I expected to return the .Left value of the parent (i.e., subfrmBaby) of whtControl: lngLeft = whtControl.Parent.Left
However, that gives me an error of: "Application or object-defined error"
When I use the immediate window to check things out I find that whtControl.Parent.Name is "frmBaby" and not "subfrmBaby" which makes it problematic to reference the subform on frmMain since I cannot figure out how to get the actual name given to the control on frmMain from the object passed to the function and so I cannot reference the subform by name either.
Questions:
How can I get the .Left value for the parent of the control passed to this function?
How can I get the actual name assigned to the subform control on frmMain? In this case, I need the name of "subfrmBaby" rather than "frmBaby."
Thanks in advance for ideas.
You can do this by iterating the controls on the main form, assuming whtControl is the form object of the subform (if it's a textbox, it's whtControl.Parent.Parent and If c.Form Is whtControl.Parent Then)
Dim mainForm As Form
Set mainForm = whtControl.Parent
Dim c As Access.Control
Dim subformControl As Access.Control
For Each c In mainForm.Controls
If TypeOf c Is SubForm Then
If c.Form Is whtControl Then
Set subformControl = c
Exit For
End If
End If
Next
If Not subformControl Is Nothing Then
Debug.Print subformControl.Left
End If
Note that iterating controls comes at a performance penalty, but this code should still take milliseconds, not seconds. Also, since we test reference equality, it works even if the same subform is present multiple times on the parent form.
I just had this issue, and I think I solved it! Thanks to Eric A's answer above to get me started. I tweaked it and built on it for my use. In my case, I needed to save the "full" address of a control to build and facilitate a control log (used to log both user actions for auditing and to allow for users to "undo" an action). I have several duplicated subforms in several sub-form controls, and a few sub-sub forms (each displaying differently filtered and sorted data), so I couldn't rely on simply knowing the subform's name, I also needed the subform control name. This also leverages others' work (as noted in the code notes with some tweaks to allow easier re-use for us. I've posted it here, hopefully it will help someone else. I know I've used SO a lot.
How we use it:
On a form, after logging an action, we record the control's ID info, which calls a function to get the toppost form (this is used in conjunction with afterUpdate event so we refresh the main form and subform). We also use the HWND to validate some other items elsewhere, and to grab a form if we don't have the initial form reference. If you use this and modify it, please point back to here and give comments.
Specific Function Code to get Control "address" and get control from address
' Posted on StackOverflow 2022 February 18 in response to Question:
' https://stackoverflow.com/q/66425195/16107370
' Link to specific answer: https://stackoverflow.com/a/71176443/16107370
' Use is granted for reuse, modification, and sharing with others
' so long as reference to the original source is maintained and you
' help lift others up as others have done those who helped with this concept
' and code.
Private Function GetControlAddress(ByRef ControlTarget As Object, _
ByRef ParentForm As Access.Form) As String
' Used in concert with building a form ID, this allows reflection back to the specific
' subform control and containing subform.
Dim ControlSeek As Access.Control
If TypeOf ControlTarget Is Form Then
' You need to dig through the whole list to get the specific controls for proper reflection down.
For Each ControlSeek In ParentForm.Controls
If ControlSeek Is ControlTarget Then
GetControlAddress = ParentForm.Name & FormIDHWNDSep & ParentForm.Hwnd & FormIDHWNDSep & ControlTarget.Name & FormIDFormSep
Exit For
ElseIf TypeOf ControlSeek Is SubForm Then
If ControlSeek.Form Is ControlTarget Then
GetControlAddress = ParentForm.Name & FormIDHWNDSep & ParentForm.Hwnd & FormIDHWNDSep & ControlSeek.Name & FormIDFormSep
End If
End If
Next ControlSeek
Else
' If you're not looking for a form, then you can skip the slow step of running through all controls.
GetControlAddress = ParentForm.Name & FormIDHWNDSep & ParentForm.Hwnd & FormIDHWNDSep & ControlTarget.Name & FormIDFormSep
End If
End Function
Public Function GetControlByAddress(ByRef StartingForm As Access.Form, ByRef strControlAddress As String) As Access.Control
' Given a control address and a starting form, this will return that control's form.
Dim ControlTarget As Access.Control
Dim TargetForm As Access.Form ' This is a reference to the hosting control
'Dim ControlSeek As
Dim FormIDArr() As String
Dim FormInfo() As String
Dim ControlDepth As Long
Dim CurrentDepth As Long
If strControlAddress = vbNullString Then GoTo Exit_Here
FormIDArr = Split(strControlAddress, FormIDFormSep)
' Because there's always a trailing closing mark (easier to handle buidling address), we skip the last array
' value, as it's always (or supposed to be...) empty.
ControlDepth = UBound(FormIDArr) - LBound(FormIDArr)
' Split out the form's Specific Information to use the details.
FormInfo = Split(FormIDArr(CurrentDepth), FormIDHWNDSep)
' The specific control is located in the 3rd element, zero referenced, so 2.
Set ControlTarget = StartingForm.Controls(FormInfo(2))
' If ControlDepth is 1 (control is on passed form) you can skip the hard and slow work of digging.
If ControlDepth > 1 Then
For CurrentDepth = 1 To ControlDepth - 1
' Note: you start at 1 because you already did the first one above.
' Split out the form's Specific Information to use the details.
FormInfo = Split(FormIDArr(CurrentDepth), FormIDHWNDSep)
Set TargetForm = ControlTarget.Form
Set ControlTarget = TargetForm.Controls(FormInfo(2))
Next CurrentDepth
End If
Exit_Here:
Set GetControlByAddress = ControlTarget
End Function
Required Helper Functions
Note, I use a property for the separators as there is some user locale handling (no included), and it also ensures that if we do change the separator it remains consistent. In this example, I simply set them to a character which is unlikely to be used in a form name. You will need to ensure your forms don't use the separator characters.
Public Function hasParent(ByRef p_form As Form) As Boolean
' Borrowed concept from https://nolongerset.com/get-top-form-by-control/
' and modified for our uses.
On Error Resume Next
hasParent = (Not p_form.Parent Is Nothing)
Err.Clear ' The last line of this will cause an error. Clear it so it goes away.
End Function
Private Function GetFormObjectByCtl(ByRef ctl As Object, _
ByRef ReturnTopForm As Boolean, Optional ByRef strControlAddress As String) As Form
strControlAddress = GetControlAddress(ctl, ctl.Parent) & strControlAddress
If TypeOf ctl.Parent Is Form Then
If ReturnTopForm Then
If hasParent(ctl.Parent) Then
'Recursively call the function if this is a subform
' and we need the top form
Set GetFormObjectByCtl = GetFormObjectByCtl( _
ctl.Parent, ReturnTopForm, strControlAddress)
Exit Function
End If
End If
Set GetFormObjectByCtl = ctl.Parent
Else
'Recursively call the function until we reach the form
Set GetFormObjectByCtl = GetFormObjectByCtl( _
ctl.Parent, ReturnTopForm, strControlAddress)
End If
End Function
Public Function GetFormByCtl(ctl As Object, Optional ByRef strControlAddress As String) As Form
Set GetFormByCtl = GetFormObjectByCtl(ctl, False, strControlAddress)
End Function
Public Function GetTopFormByCtl(ctl As Object, Optional ByRef strControlAddress As String) As Form
Set GetTopFormByCtl = GetFormObjectByCtl(ctl, True, strControlAddress)
End Function
Public Property Get FormIDHWNDSep() As String
FormIDHWNDSep = "|"
End Property
Public Property Get FormIDFormSep() As String
FormIDFormSep = ";"
End Property
Interesting. I don't think you can.
As you have seen, the parent of whtControl is its form, frmBaby.
The parent of that one is frmMain. The subform control is not part of the object chain when "going up", only when going down.
If you always use the naming scheme as in the question, you could do something like this (air code):
strSubform = whtControl.Parent.Name
strSubformCtrl = "sub" & strSubform
Set ctlSubform = whtControl.Parent.Parent(strSubformCtrl)

Word CheckBox ContentContol OnChange Event

I try to make a word document with two checkboxes where each checkbox will show/hide a part of the document with a custom style.
I plan to set value Style.Font.Hidden = True/False depending from checkbox values, but...
I found that there are 3 types of controls:
Legacy Controls - This seems old the ugly.
ActiveX Controls - I can easyly attach to checkbox onChange events, but these are also ugly and I think it's not that secure, also this is probably now working on mac.
ContentControls - This seems like the right way to do this, but I just can't attach to the right event. (Also there is some XML attachment described, but I'm not using this, this seem too complicated, I don't know.)
Can you tell me how to atach to onChange event of CheckBox ContentContol? I need the same behaviour like it's ActiveX CheckBox.
Content Controls do not have "onChange" events, so you can't get a content control to behave like the ActiveX checkbox in a simple manner. Similarly to form fields, the code for ContentControls fires when the control is entered/exited.
The only way to emulate "onChange" for a Content Control is to link the content control to a node in a CustomXMLPart in the document then work with the Document_ContentControlBeforeStoreUpdate event that triggers when the content of the node in the CustomXMLPart is going to be changed.
If, as your question indicates, this is too complex for your purposes you could use a MacroButton field that displays a font character (Symbol) that looks like a checkbox. Clicking the field would exchange that character for a different one, that looks checked. And the reverse again for the next click. Here's some sample code to get you started. If you don't like the checkboxes I chose, you can pick something else from Insert/Symbols/Symbol. Just change the character numbers and the font name.
By default a MacroButton field triggers on double click. You can change this to a single click when the document is opened in an AutoOpen macro.
Sub AutoOpen()
Application.Options.ButtonFieldClicks = 1
End Sub
Sub ToggleCheckBox()
Dim iNotChecked As Integer, iChecked As Integer
Dim rngCheck As word.Range
Dim sBkmName As String, sFontName as String
iNotChecked = 111
iChecked = 253
sBkmName = "bkmCheck"
sFontName = "Wingdings"
Set rngCheck = ActiveDocument.Bookmarks(sBkmName).Range
If Asc(rngCheck.Text) = iNotChecked Then
rngCheck.Text = Chr(iChecked)
ActiveDocument.Bookmarks.Add sBkmName, rngCheck
rngCheck.Font.Name = sFontName
ElseIf Asc(rngCheck.Text) = iChecked Then
rngCheck.Text = Chr(iNotChecked)
rngCheck.Font.Name = sFontName
ActiveDocument.Bookmarks.Add sBkmName, rngCheck
End If
End Sub

Problems when calling a public sub

I'm facing a deadend When trying to call this sub :
Public Sub backblue(ByVal frm As Form, ByVal boxname As String)
For i = 1 To 3
CType(frm.Controls(boxname & i.ToString()), TextBox).BackColor = Color.LightBlue
Next
End Sub
with button click event :
Private Sub Button1_click and bla bla....
backblue(Me, "txb1_")
End Sub
Can anybody show me a suggestion to fix the code.
It throws "Object Referrence not set to an instance bla bla" error
For information the textbox names are :
txb1_1 , txb1_2 , txb1_3
(these are some of the many textboxes in the form that i want its bakcolor changed)
and these three textboxes are already created through designer, not from execution.
i did check the textboxes names and there's nothing wrong.
the form class is also public.
if they are the only textboxs on said form you can just loop through
For Each box as Textbox In frm.Controls
box.BackColor = Color.LightBlue
Next
This error will occur if you do not declare the Form class to be public.
Also, make sure the textbox names are really correct, although this will probably cause a different error.
If you create the textboxes during execution, make sure they are initialized with New and added to the form's Controls collection.
Try this....
Public Sub backblue(ByVal frm As Form, ByVal prefix As String)
For i = 1 To 3
Dim bxName as String = prefix & i.ToString()
Dim bx as TextBox = CType(frm.Controls(bxName), TextBox)
If bx Is Nothing Then
MsgBox("Unable to find text box " +bxName)
Dim mtch() As Control = frm.Controls.Find(bxName, true)
If mtch.Length> 0 then
bx = mtch(0)
Else
Continue For
End if
End If
Bx.BackColor = Color.LightBlue
Next
End Sub
Although, a better solution would be to either create the textboxes inside a control and pass that control to BackBlue or to create an collection that has the controls and pass that in. Which brings up what is most likely yor problem your control is contained in a sub component and thus is not in the main form control collection
Alternative, you could use either the tag of the control or create a component control that implements IExtenderProvider and add it to the form --all of the above would effectively allow you to define the controls and/how they should be handled at designtime.
It may really seem that the names generated by this loop may not be the names of the original textboxes. My suggestion is before setting this Color property verify that the names generated by this loop are indeed the actual names. Maybe output this in a messagebox:
MessageBox.Show(boxname & i.ToString()) for each loop before you set the property

create a message box on application start requiring users name then display it in the program?

I would like a message box to pop-up at the start of the program asking what the customers name is. I then want this name to be displayed in a label that i have already created.
I went to application events and entered the code below after finding a few helpful tips around the internet. I get a message box allowing me to enter the customers name, so that bit works fine. The problem comes when I try to change the label. It says that 'label4' is not declared. I'm guessing that the application events section is a completely different section from the other forms.
If anyone could explain how I would go about doing this correctly and also explain the difference between so I can learn from this that would be great.
Dim message, title, defaultValue, myvalue As String
' Set prompt.
message = "Please Enter The Customers Name"
' Set title.
title = "New Customer"
' Set default value.
defaultValue = ""
' Display message, title, and default value.
myValue = InputBox(message, title, defaultValue)
label4.text = myvalue
The controls of a form a defined locally to that form, i.e. they are private members of that form and cannot be accessed from outside. Now it depends how your code is organized. If you are calling the InputBox before opening the main form then you need a way to pass the customer name to the main form. You can do that in the constructor the main form.
' In the main form
Public Sub New(ByVal customerName As String)
InitializeComponent() ' This call is required by the Windows Form Designer.
label4.Text = customerName
End Sub
Then you can create the main form like this (see also How to find the main() entry point in a VB.Net winforms app?)
Public Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
...
myValue = InputBox(message, title, defaultValue)
Dim frm As Form1 = New Form1(myValue)
' Starts the application.
Application.Run(frm)
End Sub