VBA Populating Combobox With Alternative Text - vba

New to VBA so please forgive what may seem a simple question.
Using MS Word I have produced a simple form. I have a ComboBox that is populated via an array. This works fine. What I am trying to achieve is when an option is selected in this ComboBox, an alternative text entry is actually placed into the document at a Bookmark named Advice.
I am using Bookmarks as placemarkers in the Word document. At the moment the value already defined in the ComboBox is being place in the document, instead of the alternative.
Here is my code.
Dim myArray1() As String
'Use Split function to return a zero based one dimensional array
myArray1 = Split("advice for option one|advice for option two|" _
& "advice for option three", "|")
'Use List method to populate listbox
ComboBox2.List = myArray1
Exit Sub
If ComboBox2.List = "advice for option one" Then
Advice.Text = "This piece of text for option one. It's much longer than that in the DropBox, but it is what is needed."
ElseIf ComboBox2.List = "advice for option two" Then
Advice.Text = "This piece of text for option two. It's much longer than that in the DropBox, but it is what is needed."
ElseIf ComboBox2.List = "advice for option three" Then
Advice.Text = "This piece of text for option three. It's much longer than that in the DropBox, but it is what is needed."
Else
Advice.Text = ""
End If
lbl_Exit:
Exit Sub
End Sub
I'm sure I'm doing something really silly that is stopping this from working.
Thanks!
Sorry, I've just realised that I had missed the key part. Unsurprisingly this still doesn't work.
I've provided the rest of it and included your suggestion.
Private Sub CancelBut_Click()
UserForm.Hide
End Sub
Private Sub EnterBut_Click()
Dim number As Range
Set number = ActiveDocument.Bookmarks("number").Range
number.Text = Me.TextBox1.Value
Dim Name As Range
Set Name = ActiveDocument.Bookmarks("Name").Range
Name.Text = Me.TextBox2.Value
Dim Name1 As Range
Set Name1 = ActiveDocument.Bookmarks("Name1").Range
Name1.Text = Me.TextBox2.Value
Dim Address As Range
Set Address = ActiveDocument.Bookmarks("Address").Range
Address.Text = Me.TextBox3.Value
Dim ReportDate As Range
Set ReportDate = ActiveDocument.Bookmarks("ReportDate").Range
ReportDate.Text = Me.TextBox4.Value
Dim Location As Range
Set Location = ActiveDocument.Bookmarks("Location").Range
Location.Text = Me.TextBox5.Value
Dim Reason As Range
Set Reason = ActiveDocument.Bookmarks("Reason").Range
Reason.Text = Me.ComboBox1.Value
Dim Advice As Range
Set Advice = ActiveDocument.Bookmarks("Advice").Range
Advice.Text = Me.ComboBox2.Value
Dim Office As Range
Set Office = ActiveDocument.Bookmarks("Office").Range
Office.Text = Me.TextBox6.Value
Me.Repaint
UserForm.Hide
End Sub
Private Sub ToggleButton1_Click()
If ToggleButton1.Value = True Then
ComboBox2.Visible = True
Else
ComboBox2.Visible = False
End If
End Sub
Private Sub UserForm_Initialize()
Dim myArray() As String
'Use Split function to return a zero based one dimensional array
myArray = Split("problem1|problem2|problem3|problem4|" _
& "problem5|problem6|problem7|problem8|problem9|" _
& "problem10|problem11|problem12|problem13|problem14", "|")
'Use List method to populate listbox
ComboBox1.List = myArray
Dim myArray1() As String
'Use Split function to return a zero based one dimensional array
myArray1 = Split("advice for option one|advice for option two|" _
& "advice for option three", "|")
'Use List method to populate listbox
ComboBox2.List = myArray1
End Sub
Private Sub ComboBox2_Change()
Dim Advice As Range
If ActiveDocument.Bookmarks.Exists("Advice") = True Then
Set Advice = ActiveDocument.Bookmarks("Advice").Range
Select Case ComboBox2.Value
Case "advice for option one":
Advice.Text = "This piece of text for option one."
Case "advice for option two":
Advice.Text = "This piece of text for option two."
Case "advice for option three":
Advice.Text = "This piece of text for option three."
End Select
ActiveDocument.Bookmarks.Add "Advice", Advice
End If
End Sub

You haven't shown the context in which the code is run. What's the sub, and how is it getting called? And you haven't what type of object the Advice variable is or how it got set. Your code seems to be setting the combo items and trying to act on a combo selection in the same sub. That won't work.
You should create an event procedure within the form to populate the combo when the dialog is initialized.
Private Sub UserForm_Initialize()
Dim myArray1() As String
'Use Split function to return a zero based one dimensional array
myArray1 = Split("advice for option one|advice for option two|" _
& "advice for option three", "|")
'Use List method to populate listbox
ComboBox1.List = myArray1
End Sub
The have another event procedure within the form for a combo change event:
Private Sub ComboBox1_Change()
Dim Advice As Range
If ActiveDocument.Bookmarks.Exists("advice") = True Then
Set Advice = ActiveDocument.Bookmarks("advice").Range
Select Case ComboBox1.Value
Case "advice for option one":
Advice.Text = "This piece of text for option one."
Case "advice for option two":
Advice.Text = "This piece of text for option one."
Case "advice for option three":
Advice.Text = "This piece of text for option one."
End Select
End If
End Sub
This will replace the bookmark placeholder text with the indicated text. Note: the replacement will get rid of the bookmark as well, so it will only work once unless you reset the bookmark. If you want the bookmark to remain, you need to recreate it. The range object hasn't changed, so you can use that to create the new bookmark:
Private Sub ComboBox1_Change()
Dim Advice As Range
If ActiveDocument.Bookmarks.Exists("advice") = True Then
Set Advice = ActiveDocument.Bookmarks("advice").Range
Select Case ComboBox1.Value
Case "advice for option one":
Advice.Text = "This piece of text for option one."
Case "advice for option two":
Advice.Text = "This piece of text for option two."
Case "advice for option three":
Advice.Text = "This piece of text for option three."
End Select
ActiveDocument.Bookmarks.Add "advice", Advice
End If
End Sub
So now, after you select an option in the combo box, the text in the doc will be updated, and the bookmark will be reset to the new text. So, you can make a different choice, and the text will be updated again.

Private Sub ComboBox2_Change()
Dim Advice As Range
If ActiveDocument.Bookmarks.Exists("Advice") = True Then
Select Case ComboBox2.Value
Case "advice for option one":
***Advice.Text = "This piece of text for option one."***
Case "advice for option two":
Advice.Text = "This piece of text for option two."
Case "advice for option three":
Advice.Text = "This piece of text for option three."
End Select
End If
End Sub

You are over writing the text at the bookmark with the following code which is probably run when the form is closed.
Private Sub EnterBut_Click()
...
Set Advice = ActiveDocument.Bookmarks("Advice").Range
Advice.Text = Me.ComboBox2.Value
...
End Sub

Related

Connect Bookmark to another

I have word file with VBA userform with one ComboBox1, In ComboBox1 I wrote this code for three options
Private Sub UserForm_Initialize()
ComboBox1.List = Array("Mr.", "Ms.", "Miss")
End Sub
and I have 2 Bookmarks with name Bookmark1 and Bookmark
I wrote code
Private Sub CommandButton1_Click()
Dim Bookmark1 As Range
Set Bookmark1 = ActiveDocument.Bookmarks("Bookmark1").Range
Bookmark1.Text = Me.ComboBox1.Value
End Sub
The ComboBox1 is connected to the Bookmark1 (Whatever my choice from ComboBox will appear in Bookmark1).
What I want is when Bookmark1 = "Mr." then Bookmark2 should be changed to "Manger" , and if choose "Mis." should be Changed to "student", and if choose "Miss." should be Changed to "Job seeker"
I solved it by writing a Case statement.
The code is:
Private Sub CommandButton1_Click()
Dim Bookmark1 As Range
Dim Bookmark2 As Range
Set Bookmark1 = ActiveDocument.Bookmarks("Bookmark1").Range
Bookmark1.Text = Me.ComboBox1.Value
Set Bookmark2 = ActiveDocument.Bookmarks("Bookmark2").Range
Bookmark2.Text = Me.ComboBox1.Value
Select Case Bookmark1
Case "Mr": Bookmark2.Text = "Manger"
Case "Mis": Bookmark2.Text = "student"
Case "Miss": Bookmark2.Text = "Job seeker"
End Select
End Sub

Word userform - only allowing to add data to bookmark once

I do have a userform in word which populates predefined bookmarks with values. I use following code to write the text to the bookmark:
Private Sub OKButton_Click()
Dim Text1 As Range
Set Text1 = ActiveDocument.Bookmarks("Text1").Range
Text1.Text = Me.ComboBox1.Value
When I hit the OK Button again, the text is added to the bookmark (and this can be done over and over again). This should not be possible. How can this be solved?
If the bookmark should only be written to once, I'd remove the bookmark when writing to it the first time. If the code runs again, this would cause an error, so check for the existence of the bookmark, first.
For example
Private Sub OKButton_Click()
Dim Text1 As Range
Dim doc As Document
Dim bkm As Bookmark
Dim bkmName As String
Set doc = ActiveDocument
bkmName = "Text1"
If doc.Bookmarks.exists(bkmName) Then
Set bkm = doc.Bookmarks(bkmName)
Set Text1 = bkm.Range
Text1.Text = "test" ' Me.ComboBox1.value
bkm.Delete
Else
Debug.Print "The bookmark has been removed."
End If
End Sub
Note that this approach assumes that the bookmark type is an "I-beam" type of bookmark: it marks a position in the document and contains no content.
If "bracket" bookmarks are used (the bookmark surrounds/contains at least one character) then the assigning text to the bookmark automatically deletes the bookmark. In that case, the line bkm.Delete is not required.
Usually, you would end an OK button sub with a command to close the userform, which discourages a second click:
Unload UserForm1
But if you want to make it impossible to add the text a second time, you would add a check of the existing text in the bookmark:
Private Sub OKButton_Click()
Dim Text1 As Range
Set Text1 = ActiveDocument.Bookmarks("Text1").Range
If Text1.Text <> Me.ComboBox1.value Then
Text1.Text = Me.ComboBox1.value
Else
MsgBox "That text has already been entered."
End If
End Sub

Catia VBA Automation Error Run-Time 80010005 - Selection ERROR

I have a Problem with my Userform. It should automatically Switch to another TextBox when an selection in the catpart made. I get the Automation Error: It is illegal to call out while inside message filter.
Run-time error '-2147418107 (80010005)
Sub Auswahl_Click()
Dim sel As Object, Objekt As Object, ObjektTyp(0)
Dim b, Auswahl, i As Integer
ObjektTyp(0) = "Body"
Set sel = CATIA.ActiveDocument.Selection
For i = 1 To 6
sel.Clear
UserFormNow.Controls("Textbox" & i).SetFocus
Auswahl = sel.SelectElement2(ObjektTyp, "Wähle ein Body aus...", False)
Set b = CATIA.ActiveDocument.Selection.Item(i)
If Auswahl = "Normal" Then
Set Objekt = sel.Item(i)
UserFormNow.ActiveControl = Objekt.Value.Name
sel.Clear
End If
i = i + 1
Next
sel.Clear
End Sub
' EXCEL DATEI ÖFFNEN____________________________________
Sub Durchsuchen1_Click()
Dim FPath As String
FPath = CATIA.FileSelectionBox("Select the Excel file you wish to put the value in", "*.xlsx", CatFileSelectionModeOpen)
If FPath = "" Then
Else
DurchsuchenFeld.AddItem FPath
ListBox1.Clear
ListBox1.AddItem "Bitte wählen Sie das Panel"
TextBox1.SetFocus
End If
End Sub
' FORMULAR SCHLIEßEN____________________________________
Sub ButtonEnd_Click()
ButtonEnd = True
Unload UserFormNow
End Sub
First you have to know that when you use an UI and still want to interact with CATIA, you have to choices:
Launch the UI in NoModal: mode UserFormNow.Show 0
Hide the UI each time you want to interact with CATIA: Me.Hide or UserFormNow.Hide
Then, I strongly recommend you to avoid looking for items with names:
UserFormNow.Controls("Textbox" & i).SetFocus
If you want to group controls and loop through them, use a Frame and then use a For Each loop.
For Each currentTextBox In MyFrame.Controls
MsgBox currentTextBox.Text
Next
Regarding your code, many simplifications can be done:
Private Sub Auswahl_Click()
Dim sel As Object
Dim currentTextBox As TextBox
Dim Filter As Variant
ReDim Filter(0)
Filter(0) = "Body"
Set sel = CATIA.ActiveDocument.Selection
'Loop through each textbox
For Each currentTextBox In MyFrame.Controls
sel.Clear
'Ask for the selection and test the result at the same time
If sel.SelectElement2(Filter, "Wahle ein Body aus...", False) = "Normal" Then
'Get the name without saving the object
currentTextBox.Text = sel.Item2(1).Value.Name
Else
'allow the user to exit all the process if press Escape
Exit Sub
End If
Next
sel.Clear
End Sub

Excel - Returning the caption of the selected option button

Probably a silly question with a simple answer but I am a real novice when it comes to userforms.
I have "Frame 3" with 5 different option buttons (Dest1, Dest2, Dest3, Dest4, Dest5) After an option is selected, where is the caption value of the selected option stored? How can I access that with vba.
Thank you,
Josh
Here's just some example code you can use. Add your Option Buttons to groups, and then you can go from there. I used groups since you had multiple frames, and you can check based on group, and have multiple groups, and check which one's selected for each group.
Private Sub CommandButton1_Click()
Dim x As Control
' Loop through ALL the controls on the UserForm.
For Each x In Me.Controls
' Check to see if "Option" is in the Name of each control.
If InStr(x.Name, "Option") Then
' Check Group name.
If x.GroupName = "Grp1" Then
' Check the status of the OptionButton.
If x.Value = True Then
MsgBox x.Caption
Exit For
End If
End If
End If
Next
End Sub
You can also access the option buttons through the frame-ojbect that holds them (if you have other frames and controls you don't want to go through):
Option Explicit
Sub Test()
Dim oCtrl As Control
'***** Try only controls in Frame3
For Each oCtrl In Frame3.Controls
'***** Try only option buttons
If TypeName(oCtrl) = "OptionButton" Then
'***** Which one is checked?
If oCtrl.Value = True Then
'***** What's the caption?
Debug.Print "You have checked option " & oCtrl.Caption
Exit For
End If
End If
Next
End Sub
The Label Text associated with an Option Button is obtainable by using OptionButton1.Caption
If you are using a loop, just substitute the OptionButton1 with your variable for option buttons and it will pull through the one you need when conditions are met. eg:
For xitem = 1 To 5
xFrm = "OptionButton" & xitem
For Each fItem In Me.Controls
If fItem.Name Like xFrm Then
If fItem.Value Then
k = fitem.Caption
End If
End If
Next fItem
Next xitem
In my case, I wanted the caption of the toggle that was selected in an option group to be passed on to a subform filter. e.g. choosing toggle "black" filters subform to all cars where strColour = "black".
I ended up with this:
Private Sub OptionGroupName_Click()
Dim Caption As String
Caption = OptionGroupName.Controls.Item(OptionGroupName.Value - 1).Caption
Me.SubformName.Form.Filter = "[SubformField] = """ & Caption & """"
Me.SubformName.Form.FilterOn = True
End Sub
Not to dog pile on everyone else's options but I created a function that takes the radio group name and spits out the selected radios coresponding label caption. Was using it in Access not Excel.
Only works provided you name your controls similarly....
i.e. (lblRadioButton1 & optRadioButton1)
Function GetSelectedRadioButtonCaption(ByVal optionGroupName As OptionGroup) As String
Dim oCtrl As Control
Dim oCtrl2 As Control
Dim optionLabelName As String
Dim optionLabelObject As Label
Dim optionButtonObject As OptionButton
For Each oCtrl In optionGroupName.Controls
'***** Try only option buttons
If TypeOf oCtrl Is OptionButton Then
'***** Which one is checked?
Set optionButtonObject = oCtrl
If optionButtonObject.OptionValue = optionGroupName.Value Then
'***** What's the caption?
optionLabelName = Replace(oCtrl.Name, "opt", "lbl")
For Each oCtrl2 In optionGroupName.Controls
If oCtrl2.Name = optionLabelName Then
Set optionLabelObject = oCtrl2
GetSelectedRadioButtonCaption = optionLabelObject.caption
Exit For
End If
Next
End If
If GetSelectedRadioButtonCaption <> "" Then
Exit For
End If
End If
Next
Exit_GetSelectedRadioButtonCaption:
End Function

How can I check whether the data already exists in combobox list?

How can I check if the data from cmbTypeYacht.text already exists in cmbTypeYacht.list?
Here's what I've got:
Dim TypeYacht As String 'Type of yacht input
TypeYacht = cmbTypeYacht.Text
If TypeYacht = ("cmbTypeYacht list") Then
MsgBox "Type of Yacht is already on the list", vbExclamation, "Yacht Chantering"
Else
cmbTypeYacht.AddItem cmbTypeYacht.Text
With cmbTypeYacht
.Text = ""
.SetFocus
End With
End If
sorry about the tag im not quite sure which is it but im using Microsoft Visual Basic app.
The ComboBox class has a FindStringExact() method that will do the trick for you, like this:
Dim resultIndex As Integer = -1
resultIndex = cmbTypeYacht.FindStringExact(cmbTypeYacht.Text)
If resultIndex > -1 Then
' Found text, do something here
MessageBox.Show("Found It")
Else
' Did not find text, do something here
MessageBox.Show("Did Not Find It")
End If
You can also just loop through the list as well, like this:
Dim i As Integer = 0
For i = 0 To cmbTypeYacht.Items.Count - 1
If cmbTypeYacht.Items.Contains(cmbTypeYacht.Text) Then
MessageBox.Show("Found It")
Exit For
End If
Next
I'm working in Excel 2013 and there is no FindStringExact or .Items.Contains so, neither of those are valid. There is also no need to iterate the list. It is very simple actually. Given a userform "MyUserForm" and a combobox "MyComboBox",
If MyUserForm.MyComboBox.ListIndex >= 0 Then
MsgBox "Item is in the list"
Else
MsgBox "Item is NOT in the list"
End If
Explanation: If selected item is not in the list, .ListIndex returns -1.
The combobox in vba has a property called MatchFound. It will return true if the value you inputted in the combobox (ComboBox.Value) existed before.
Put below code in the update event of the combobox for trial
Private Sub ComboBox_AfterUpdate()
If ComboBox.MatchFound = True then
Msgbox "Value exist"
End If
End Sub
Check it out:
https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/combobox-matchfound-property-outlook-forms-script
You do not need to iterate through combobox.items. Items.Contains will already iterate through the list for you.
Simply use:
If cmbTypeYacht.Items.Contains(cmbTypeYacht.Text) Then
MessageBox.Show("Found It")
Exit For
End If
Searching: VBA check whether the data already exists in combobox list?
but vba doesnt have the properties above.
Sub TestString()
Dim myString As String
Dim i As Long
Dim strFound As Boolean
'Just for test purposes
myString = "Apple"
strFound = False
With Me.ComboBox1
'Loop through combobox
For i = 0 To .ListCount - 1
If .List(i) = myString Then
strFound = True
Exit For
End If
Next i
'Check if we should add item
If Not strFound Then .AddItem (myString)
End With
End Sub
This was found after a lot of searching at http://www.ozgrid.com/forum/showthread.php?t=187763
and actually works