Use string variable to set object variable in VBA? (Excel 2013) - excel

I have a number of ActiveX controls/buttons on a page, and I would like to modify several of the parameters of the buttons (in a loop function).
I am fine with writing the loop function to achieve this, but cannot find a way to refer to the object using a string variable. I have set up an object variable (as per below), and a string variable to be used to change the reference for the object variable - but can't find a way to get it to work.
This is the code that does NOT work:
Private Sub TrialCode_Click()
Dim ButtonObj As Object
Dim ButtonCaption As String
Dim ButtonString As String
ButtonString = "CommandButton1"
Set ButtonObj = ButtonString
ButtonCaption = "Something"
ButtonObj.Caption = ButtonCaption 'example of the kind of parameters I want to change
End Sub
The Set ButtonObj = ButtonString is the command that fails, reporting a Type Mismatch error.
I'm working in Excel 2013.
I really hope there is some way to do this. Any help will be really appreciated!!!

The CommandButton belongs to an OLEObject
try
ButtonString = "CommandButton1"
Set ButtonObj = ActiveSheet.OLEObjects(ButtonString)
ButtonCaption = "Something"
ButtonObj.Object.Caption = ButtonCaption 'example of the kind of parameters I want to change
Note that some properties occur directly under ButtonObj, others such as Caption sit below Object

Related

How to save Dictionary object to bin file in VBA?

This is VBA case. I want to save Dictionary object to bin file and put it again back to Dictionary later. This object should be the only content of bin file. In general I am stuck on:
Compile error: Can not Get or Put an object reference variable or a
variable of user-defined type containing an object reference
Relevant part of code looks like this:
Public generalListOfAddIns As Object
Public Type BinaryCapsuleType
forObject As Object
End Type
Public Sub CreateGeneralListOfAddIns()
Set generalListOfAddIns = CreateObject("Scripting.Dictionary")
End Sub
Public Sub SaveDictAsBin()
Dim Capsule As BinaryCapsuleType
Set Capsule.forObject = generalListOfAddIns
Dim filePath As String
Dim fileNo As Integer
Dim loadedGeneralListOfAddIns As Object
filePath = "C:\TestFolder\ListOfAddIns.bin"
fileNo = FreeFile
Open filePath For Binary Lock Read Write As #fileNo
Put #fileNo, , Capsule
Close #fileNo
End Sub
I tried and didnt helped:
Both early binding and late binding
Save Dictionary direcly
Encapsulate Dictionary using the Type statement (as in code example)
I would like to avoid:
Saving Dictionary content into text files
Transforming Dictionary into Array for saving purpose
Adding more references into VBA Project
Which sources didnt helped me (or I dont understand them):
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/can-t-get-or-put-user-defined-type-containing-object-reference
https://analystcave.com/excel-saving-your-vba-data/
Thank you very much for any help or ideas, RosMane

How to use String value as a dot operation in VBA? it is possible?

Sub getTrailInfo()
Dim attr As Variant
Dim attrTB As String
attrNames = Split("trailName,trailType,aSideSite,zSideSite,status", ",")
Dim trailForm As New formTrailInfo
For Each attr In attrNames
attrTB = attr + "TB"
trailForm.attrTB = attr
Next attr
trailForm.Show
End Sub
When I run the above code it gives a compilor error: Method or Data not found at line trailForm.attrTB = attr
I have required variables in attrNames String array. I need to put values of these variables in corosponding textboxes in a userForm. The name of Text Box in this userForm is attrNameTB. For example Text box for trailName is trailNameTB.
You cannot use VBA like that.
When you start your code, the compiler will first compile the code and check that you want to access a property named attrTB of your form. This doesn't exist and you will get the error you mentioned.
The compiler cannot wait until your variable attrTB has an actual value and then guess that you don't want a property with that name, but use the content of that variable as property name.
However, every form has a collection of all it's controls (button, edit boxes, combo boxes, labels...), and you can access the members of a collection either by index or by name. As you have the name of the control in attrTB, you could simply write
trailForm.Controls(attrTB).Text = attr

Find / replace text in embedded word object code stopped working

I have used this code successfully to replace content in an embedded word object from excel. I copied the code for a new excel file but now it doesn't work. It opens the file but doesn't replace although I can see that it IS finding the right text and replacement text. I'm kind of lost as to what is happening.
Dim strFindText As Range
Dim strReplaceText As Range
Dim nSplitItem As Long
Set strFindText = ActiveWorkbook.Worksheets("Utilisation Form").Range("c11:c20")
Set strReplaceText = ActiveWorkbook.Worksheets("Utilisation Form").Range("a11:a20")
nSplitItem = strFindText.Count
Debug.Print strFindText.Item(0)
For Each sh In ThisWorkbook.Sheets("Utilisation Form").Shapes
If sh.Name <> "Object 1" Then sh.Delete
Next
Set urobj = ThisWorkbook.Sheets("Utilisation Form").OLEObjects("Object 1")
Set wordtemp = urobj.Duplicate
wordtemp.Verb Verb:=xlOpen
Set wordtemp2 = wordtemp.Object
For x = 1 To nSplitItem
With wordtemp2.Content.Find
.Forward = True
.Text = strFindText.Item(x)
.ClearFormatting
.Replacement.Text = strReplaceText.Item(x)
.Execute Replace:=wdReplaceAll
End With
Next x
End Sub
Thanks for the support
When the early-binding technology is used in the code you need to add a corresponding COM reference to be able to use data types. Otherwise, you need to declare everything from the Word object model as Object in the code and use the late-binding technology.
To use early binding on an object, you need to know what its v-table looks like. In Visual Basic, you can do this by adding a reference to a type library that describes the object, its interface (v-table), and all the functions that can be called on the object. Once that is done, you can declare an object as being a certain type, then set and use that object using the v-table. For example, if you wanted to Automate Microsoft Office Excel using early binding, you would add a reference to the Microsoft Excel X.0 Object Library from the Project|References dialog, and then declare your variable as being of the type Excel.Application. From then on, all calls made to your object variable would be early bound.
Read more about that in the Using early binding and late binding in Automation article.

How can I use cell value in declaration of new class object?

I have a fairly simple question to which I can't seem to find the answer anywhere so I'll try here. I have created a new class called "Groups" in vba. What I want to do is retrieve a value from a cell in excel and use this as the name of the new group I want to create. I've tried accessing the value through Range("B20").Value but then I need to store it in another variable first and if I do that I can't use it as the name after since it thinks I want the group to be named like my variable I stored it in.
Does anyone know a way around this? Appreciate any help or suggestions.
Below is what I've tried which doesn't work.
Dim Range("B20").Value As Group
I've also tried this but then it thinks I want to name the group as my variable "getName"
Dim getName As String
getName = Range("B20").Value
Dim getNAme As Group
Kind regards,
Jahlove
As others have suggested in the comments, you cannot change a string variable into a variable name. However, if all you want to access/reference an object using a string, you can try a Scripting.Dictionary (docs here) like this:
Sub DynamicGroupNaming()
Dim sGroupName As String
Dim dictGroups As Object
Set dictGroups = CreateObject("Scripting.Dictionary")
'Change Sheet1 to the name of your worksheet
sGroupName = ThisWorkbook.Sheets("Sheet1").Range("B20").Value
' Add a new group to the dictionary
dictGroups.Add sGroupName, New Group
' Access the group's properties/methods in the usual way
dictGroups(sGroupName).Name = sGroupName
MsgBox dictGroups(sGroupName).Name
Set dictGroups = Nothing
End Sub

Option Explicit - Not sure how to dim this

I have an existing macro that I use to format columns. I've been using this without problems. Now, I'm looking to learn how to use Option Explicit and I am running into a problem with defining my variable.
What should I be dim'ing Level as? I tried Dim Level As String but that didn't work. I'm trying to get a better understanding so any feedback would be appreciated.
Option Explicit
Sub adviseformat()
Dim Form As Worksheet
Set Form = Sheets("Formatting")
With Form
Level = WorksheetFunction.Match("Level", .Rows("1:1"), 0)
.Columns(Level).Delete
.Columns("D:E").Delete
.Range("U:U").Value = Range("E:E").Value
.Columns("E").EntireColumn.Delete
.Columns("F:I").Delete
.Columns("I").Delete
.Columns("L").Delete
.Columns("M").Delete
Form.Range("A:B").EntireColumn.Insert
Form.Range("A1").Value = "Owner"
Form.Range("B1").Value = "Comment"
Form.Range("A1").Interior.Color = 65535
Form.Range("B1").Interior.Color = 65535
Form.Range("O1").Interior.Color = 65535
End With
End Sub
As you type the WorksheetFunction.Match part, the VBA editor should pop up and give you a clue to the return type. It should say something like:
Match(Arg1, Arg2, [Arg3]) as Double
The "As Double" part tells you the return type of the Match function. This is the type you should use to declare your Level variable.
Looking on MSDN, I found this :
MATCH returns the position of the matched value within lookup_array, not the value itself.
For example, MATCH("b",{"a","b","c"},0) returns 2, the relative position of "b" within the array {"a","b","c"}.
So my guess is that you should use Dim Level As Variant

Resources