If I put:
variableName = namecombobox.selectedItem
or
Dim variablename as type = namecombobox.SelectedIndex
Visual Studio gives me the error
Option Strict disallows conversions from object to string.
I can fix this by putting:
variableName = convert.ToString(namecombobox.SelectedItem)
Are all values contained in a combobox automatically treated as a non-string even when they are string values (in this case "Male" & "Female") and what is the correct way of assigning the value selected in a combobox to a variable?
This is normal, the ComboBox.Items property is a collection of System.Object. You should use the item's ToString() method, just like ComboBox does to generate the visible text.
Dim variableName As String = namecombobox.SelectedItem.ToString()
Or use CStr(), the VB.NET way.
If you are using this, assuming you select 'Selection1' on the combo box:
Dim x As Boolean
Dim MyVariable As String = ""
MyVariable = ComboBox1.SelectedItem.ToString()
If MyVariable = "Selection1" Then
x = True
Else
x = False
Pretend the above code is YOUR code... This is CORRECT for selecting strings from a ComboBox. Insert a breakpoint on the IF statement checking "MyVariable"- you will see the variable content if you hover your mouse over the variable name. It is a quick way to view the contents of your variable. If hovering above the variable shows an empty string ("") or simply Nothing, then it hasn't picked up any selected item.
In my code above, if I clicked an item containing the words "Selection1", the 'MyVariable' would contain a String of "Selection1" and the boolean variable 'x' would also read as TRUE.
If you're getting reading errors by comparing the variable you have issues elsewhere in your code.
Related
I want to update a word field content using VBA. I already have a code that works, but I have to refer to the field's index instead of field's name, which I would prefer.
The code I have is as follows:
Sub UpdateField()
Dim myString As String
myString = "asdf"
ActiveDocument.Fields(1).Result.Text = myString
End Sub
Suppose that the field's name is MyField1. The following code will not work (I get the Run-time error '13': Type mismatch'.
Sub UpdateField()
Dim myString As String
myString = "asdf"
ActiveDocument.Fields("MyField1").Result.Text = myString
End Sub
I create my word fields from File Menu > Informations > Advanced Properties > Custom Tab.
So, how to refer to the field's name when we want to update its content?
These are DocProperty fields. If you press Alt+F9 you'll see the field codes.
A DocProperty field references (links to) a Document Property. The Document Property has the name, but this does not "name" the field. Nor is it possible to update a DocProperty field directly since it links to the Document Property. It might be possible to make it temporarily display something else, but this will be lost any time the field is updated.
In order to update a DocProperty field it's necessary to update the underlying Document Property. For example
Sub EditDocPropUpdateDocPropertyField()
Dim doc As Word.Document
Dim prop As Office.DocumentProperty
Dim propName As String
Dim newPropValue As String
Set doc = ActiveDocument
propName = "MyField"
newPropValue = "new value"
Set prop = doc.CustomDocumentProperties(propName)
prop.value = newPropValue
doc.Fields.Update
End Sub
In the VBE, the Object Browser is a great way to find out what's possible. When I find Word>Field and click on it, I see a list of the members of Field. Name is not in that list. This means that the field object does not have a Name property. That's why you get the error.
You can work around this. One way is to create a bookmark around the field in question. Then in code, find the bookmark by name, then find the field by index inside the bookmark range.
Sample to set text to fields by field name:
ThisDocument.FormFields.Item("MyField1").Result = "hello"
On my access form, I have a text box that will be a string of characters with multiple "/"s throughout the string. I want to use the split function to separate this string into a list of values to use for my combo box on a subform.
I know it's somewhere along the lines of:
Public Function MakeList()
Dim MyList as String
Dim txt as String
txt = [myTextBoxField].Value
MyList = Split(txt,"/")
Either:
[myComboBox].Value = MyList
Or:
[myTextBoxField].Value = MyList
End Sub
I am not sure if this is supposed to be on "Form Load" or in a module for the Public Function.
All other code shows a For Loop or Debug.Print. I am looking to store this list as a field in my table and then use that field for my Row Source in my combo box.
First, combobox RowSourceType property must be set to ValueList. Next, VBA sets RowSource property, not Value. List is not a property of combobox in Access. Simply:
Me.myComboBox.RowSource = Replace(Me.myTextBoxField, "/", ";")
Form Load event should be appropriate.
Background
I have serialized a tab control's property, selected tab. I Am using two objectlists to store the object preset object that is being serialized.
Dim _allPresetsList As New List(Of PresetObject)
Dim _XmlPresetsList As New List(Of PresetObject)
preset.TabPageProperty = TabControl1.SelectedTab.ToString()
Dim objStreamWriter As New StreamWriter(_XmlLocation)
Dim xml As New XmlSerializer(_allPresetsList.GetType)
xml.Serialize(objStreamWriter, _allPresetsList)
objStreamWriter.Close()
Code used to de-serialize
Dim objStreamReader As New StreamReader(_XmlLocation)
_XmlPresetsList = xml.Deserialize(objStreamReader)
objStreamReader.Close()
However I cannot convert it back, this is how I have done it successfully with other controls.
CheckBox1.Checked = _XmlPresetsList(0).CheckBox1Property.ToString()
This does not work though
TabControl1.SelectedTab = _XmlPresetsList(0).TabPageProperty.ToString()
I am getting this error
Value of type 'String' cannot be converted to
'System.Windows.Forms.TabPage'.
Question
How can I convert the tab control string property from string back?
This is what is probably causing your error:
preset.TabPageProperty = TabControl1.SelectedTab.ToString()
This is just going to save something like "TabPage: {TabPage1}". Since SelectedTab is an object property, it cant be serialized and saving the type name of it wont be much help in determining which was selected. As the error states you cant make a TabPage object from a string. Instead save and restore something simpler like the selected index:
preset.TabPageIndex = TabControl1.SelectedIndex
I am not sure of the internals of the PresetObject, but I would use typed properties - in this case Int32 rather than string. The serializer will convert back and forth for you.
You should also turn on Option Strict.
CheckBox1.Checked = _XmlPresetsList(0).CheckBox1Property.ToString()
Checked is a boolean, yet you are assigning a string value to it. Option Strict on will warn you when you are leaving VB to make this type of conversion.
I'm trying to assign text from "comp" in the form "home" to a textbox with the name "d1" in the form "home".
but this needs to be done with a counter in the form "home".
The code is in a module.
What I've tried=
home.controls("d" & home.counter).text = home.comp.text
I keep getting an error:
use the new keyword to create an object instance ==> the textbox exists in the form
check to determine if the object is null before calling the method ==> the textbox is empty
get general help for this exception
You could use Controls.Find:
Dim controls = home.Controls.Find("d" & home.counter, True)
If controls.Length > 0 Then
Dim txt = TryCast(controls(0), TextBoxBase)
If txt IsNot Nothing Then
txt.Text = home.comp.text
End If
End If
However, normally i would not use this approach since it's error-prone. Why don't you provide a public property in the Home-form that you can access? This property would get/set the TextBox' Text.
For example:
Public Property HomeCompText As String
Get
Return txtHomeComp.Text
End Get
Set(value As String)
txtHomeComp.Text = value
End Set
End Property
Now you can use this clear, safe and maintainable code:
home.HomeCompText = home.comp.text
You could even change the underlying control.
I'm trying to create a worksheet that creates a list of values that will be used to initialize the values of an instantiated class.
For example, I might have the following in my initialization worksheet:
Property Name Value
StartingCol A
StartingRow 11
I'd then create a class that would parse this worksheet and provide me with an enumberable that I could use to initialize the properties of an instantiated object. However, I'm not sure how I might be able to specify the property value at runtime using a string rather than specifying it explicitly in code. You can get an idea of what I'm trying to accomplish in the code below:
Sub test_PropertyAssignment()
Dim sp As SheetParser
Dim strFieldName As String
Dim strFieldNameValue As String
Set sp = New SheetParser
'The property name is supplied explicitly'
sp.StartingCol = "B"
strFieldName = "StartingCol"
strFieldNameValue = "B"
sp.[how can I supply strFieldName to specify the property?] = strFieldNameValue 'Will not Work'
End Sub
Is there a way to use a string at runtime to specify the property name rather than specifying explicitly in code?
Look up the CallByName function in the VBA help.
You should be able to do something like:
Call CallByName(sp,strFieldName,vbLet,strFieldNameValue)