Store location of command button cell address to variable in VBA - excel

Okay so I'm using Excel and trying to get a cell address based off the location of the command button I'm clicking. I want to store that cell address in a variable as I click the button to be used in the next code for the user form that pops up as a result of clicking that button. Ive looked at this link: Store location of cell address to variable in VBA , which is similar to what I'm trying to do but I cant seem to get it to work with the ActiveSheet.Shapes(Application.Caller).TopLeftCell.Address that gives an address based off the top left corner of the command button. I'm trying to do it this way so I can use the same code from the next part for every similar button I add without having to manually change the code based off where the button is.
I'm pretty new when it comes to Excel and VBA so any help would be appreciated.
Edit:
I tried adding the code but I'm getting a Runtime error '1004' Unable to get Buttons property of the Worksheet class. I have this
Sub Button2_Click()
Dim BtRng As Range
Set Btnrng = ActiveSheet.Buttons(Application.Caller).TopLeftCell
MsgBox Btnrng.Address
Btnrng.Offset(3, 3) = "Hello"
formAddBill.Show
End Sub
This button is also popping up a userform for information input. the error is happening on Set Btnrng = ActiveSheet.Buttons(Application.Caller).TopLeftCell

If you are using application.caller then I assume your buttons are from the forms.control toolbox. This makes life a lot easier.
Assign each button with this code example:
Sub Rng_Butn_Clicked()
Dim BtRng As Range
Set Btnrng = ActiveSheet.Buttons(Application.Caller).TopLeftCell
MsgBox Btnrng.Address
Btnrng.Offset(3, 3) = "Hello"
End Sub
If you are using command buttons from the activex toolbar, it can get a bit confusing. Doing it one at a time is easy enough
Private Sub CommandButton1_Click()
Me.CommandButton1.TopLeftCell.Offset(0, 1) = "Hi"
Me.CommandButton1.TopLeftCell.Offset(, 2).Interior.Color = vbBlue
MsgBox Me.CommandButton1.TopLeftCell.Address
End Sub
But assigning one code to many activex command buttons is not as easy, I would prefer to use the Forms Buttons if you want to assign one code to many buttons.
Edit: If you are getting this error
You probably put the code in a command button. Please reread my answer.
This is what I am referring to:Form Controls & ActiveX Controls

Related

Excel VBA - Save Userform Changes

Is it possible to save changes to a Label Caption in a userform in Excel VBA, so that they are permanently saved, and only changed when you enter a new change?
I have checked, that the code is changing the caption, but I cannot get it to stick, so that it is still there next time I open the userform.
Thank you in advance
Private Sub cmdSubmit_Click()
'resets participants email and name
If Me.optProg.Value = True Then
Me.NameLabelProg.Caption = Me.CB_Part.Value
Me.MailLabelProg.Caption = Me.TB_Mail.Value
ElseIf Me.optTester.Value = True Then
Me.MailLabelTest.Caption = Me.CB_Part.Value
Me.NameLabelTest.Caption = Me.TB_Mail.Value
End If
End Sub
Check out this userform example and you'll find answers to many of your questions.
Source of userform
Forgive the lengthy answer initially, but there is a bit of a risk involved with making permanent changes to UserForms through VBA.
In order to change the caption of a Label (or UserForm or any other Control permanently, you will have to "Trust access to the VBA project object model" in order to do it via VBA code. Now, while this is possible it is not usually recommended because it can seriously put a user's PC at Risk should they encounter a Macro developed for nefarious purposes.
(To clarify in case the question is raised, your end user(s) will have to make this Trust setting change on their PC's as well . . . you cannot make the change on your PC, setup the code to work and then hand the file over to another user and have it work on their PC without them making the same change.)
There are methods to do this programmatically, but, this falls into the "nefarious Macro" rabbit hole and would need to be disclosed to the end user you are making this change. . . Research at your own risk.
If you are OK with putting yourself at risk, you can do it using VBA similar to the following snippet I found here. You will have to substitute your UserForm name and Label name as appropriate. I tested it on my own UserForm and it works as expected.
Sub Change_Userform()
ThisDocument.VBProject.VBComponents("Userform1").Designer.Controls("Label1").Caption = "Some new caption text"
End Sub
You will need to do some research on how to "Trust access to the VBA project object model" yourself and understand the risks to do this in order for the above code to work.
If I understand the intent of what you are trying to accomplish correctly though, you could achieve this effect without having to put yourself or your end user(s) at risk.
(Most end user(s) typically would not have direct access to the VBA Designer where they would see the UserForm's un-initialized environment.) To do this, you would have to place your code in the UserForm's event.
The following assumes your Me.optProg.Value and Me.optTester.Value are Option Buttons which a user would change. If you create a "Settings" sheet in the file, you can place values in the cells of this sheet and then hide it so the users do not modify them directly. Then, reference the values of the cells and change the appearances of the Option Buttons at the same time as the UserForm's launch. (Additionally, you can set the Click events of the Option Buttons to change the values of the same cells and provide that change to affect the UserForm's Initialize event when called, but this should get you going in the right direction.)
Sub UserForm_Initialize()
'The Range below is completely up to you.
'Since you are using Boolean True/False, a simple "1" or "0" _
is easy to use to make the changes.
If Thisworkbook.Sheets("Some_Settings").Range("A1").Value = "1" Then
Me.optProg.Value = True
Else
Me.optTester.Value = True
End If
'do some other code here as needed to finish initializing the UserForm
If Me.optProg.Value = True Then
Me.NameLabelProg.Caption = Me.CB_Part.Value
Me.MailLabelProg.Caption = Me.TB_Mail.Value
ElseIf Me.optTester.Value = True Then
Me.MailLabelTest.Caption = Me.CB_Part.Value
Me.NameLabelTest.Caption = Me.TB_Mail.Value
End If
End Sub

Get command button by using cell address

I want to call/ activate a button at the end of a Sub. I know the cell address of the command button, but I don't know the name/ID of the button.
How do I select/activate the button without looping through each button on active sheet?
https://stackoverflow.com/a/30600479/13049793
I have created my buttons on multiple rows with each assigned to the same macro, from my understanding, I cannot call the macro the button is assigned to because the macro uses the button's relative position, below is a simple example to illustrate the use of the buttons relative position:
Sub ExampleButtonClick()
Dim Cellvalue As String
Cellvalue = ActiveSheet.Buttons(Application.Caller).TopLeftCell.Offset(0, -1).Value
Msgbox (Cellvalue)
End Sub
i assume you want to run one macro that at the end initiates a different macro, i also assume the reason the button is rather not as a sub that is just called is because it has its independent function that can be used without the other sub
assuming that you used a command button as an activeX control, why not just use a private sub that the button performs and place that in an individual module and at the end of your current sub;
call module1 'assuming the private sub exists in module 1
or rather include the code even if duplicated in the first sub, searching for a button seems the circular route unless there is another intention you wish to pursue.
maybe elaborate on the task at hand or post the current code you are working on?

Determining GroupBox from OptionButton errors out but expanding variable properties in locals window fixes issue

I have an Excel sheet set-up with four radio buttons (option buttons) inside of a groupbox. It looks like this: Excel Sheet Setup.
The following code should return the caption of the groupbox ("Buttons").
Sub rad_change2()
Dim button As OptionButton
Set button = ActiveSheet.OptionButtons.Item(2)
Debug.Print (button.GroupBox.Caption)
End Sub
When the code runs, there is an error on the Debug.Print line. When this happens, I can go into the locals window, and click the [+] icon to expand the properties for button. After expanding the properties in the locals window, I can press resume on the code and the code finishes running as it should and returns the caption of the groupbox.
What do I need to do to get the code to run without getting an error? Why does expanding the object properties in the local windows resolve the error? The code seems to be correct, as it does do what I need it to do, but I need it to do so without any errors in the process.
I'm using the Excel through Office 365, version 2003 (build 12624.20320).
Along with expanding the button properties to get the code to finish working after a breakpoint, I discovered that hovering over the button variable to preview its value also works. This had me wondering if the value or a property of the button needed to be accessed before I tried to get the caption property of the groupbox property. I'm not sure why I would have to do this, but it ended up working.
The following code does the trick.
Sub rad_change2()
Dim tempString As String
Dim button As OptionButton
Set button = ActiveSheet.OptionButtons.Item(2)
tempString = button.Name
Debug.Print (button.GroupBox.Caption)
End Sub
Instead of using a variable tempString, the button.Name could be displayed with a messagebox or Debug.Print for the same effect.

Using the value of a textbox in a userform to activate another textbox on a worksheet

Firstly, I am as beginner as beginner gets.
I am trying to take the value from a text box embedded in a user form and then using it in another line of code to activate another text box on a worksheet.
Private Sub CommandButton1_Click()
UserForm2.Hide
Dim FieldName As String
FieldName = UserForm2.TextBox1.Value
Worksheets("Quote").FieldName.Activate
End Sub
I hope you can see what I'm attempting from this code. The error is "Run-time error '438': Object doesn't support this property or method".
The value obtained from the textbox is identical to the name of the other one and has been tested to see if it can be retrieved or not.
If someone could tell me the correct functions to use, it'd be much obliged.
Concerning the name of your Sub - Private Sub CommandButton1_Click, I assume that the button is in a form and the TextBox is in a worksheet. In general, there are two types of TextBoxes in Excel - ActiveX control or a Form control and they are handled differently:
What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?
If you are not sure whether the TextBox is an ActiveX control or a ControlElement, then the following would work. Somehow.
Private Sub CommandButton1_Click()
On Error Resume Next
Dim NameOfTextBox As String
NameOfTextBox = UserForm2.TextBox2.Value
Worksheets(1).OLEObjects(NameOfTextBox).Activate
Worksheets(1).Shapes(NameOfTextBox).Select
Unload Me
On Error GoTo 0
End Sub
Caution: This is a good example of a "quick and dirty" code, consider only using it for learning reasons.
In production, it is really a good idea to use the Forms as they are supposed to be used (see https://codereview.stackexchange.com/questions/154401/handling-dialog-closure-in-a-vba-user-form) and try to avoid On Error Resume Next.

Rowsource not working via VBA

I can't get the RowSource property of a list box to update via VBA. From another thread, I found the syntax, so I think this is correct. But, despite not failing, it doesn't do anything to the RowSource property (it remains blank). Below:
frmAddIngredient is the user form.
lbxIngredient is a listbox control in that form.
UniqueIngredients is one of the sheets in the workbook.
NumberOfItems is 1 (in this case).
It doesn't give an error, but it doesn't change anything, either. The form itself is not active at this time. This code is supposed to set up the form for later showing.
frmAddIngredient.lbxIngredient.RowSource = Sheets("UniqueIngredients").Range("A1:A" & CStr(NumberOfItems)).Address
The most recent code is
frmAddIngredient.lbxIngredient.RowSource = "=UniqueIngredients!A1:A1"
but, it still doesn't change anything in the actual form.
Also, can I add a new post, or do I have to continue editing this one and adding stuff?
What you want (as discussed in the comments on your question) is not possible. Setting something by code does not change it's property in the properties window and is only so until your project resets.
Consider a Userform with 2 buttons, with their original name and caption and then in a module paste these 2 subs.
Sub demo1()
UserForm1.CommandButton1.Caption = "Demo 1"
UserForm1.Show
End Sub
Sub demo2()
UserForm1.CommandButton2.Caption = "Demo 2"
UserForm1.Show
End Sub
When you run the first Sub demo1 Button 1's caption has changed but Button 2's caption has not.
Close the Userfom and now run demo2, you'll see that Button 1's caption is back to it's original hard set (properties window) name and that now Button 2 has a different name.

Resources