Trigger same macro with different command button with Button properties - excel

As the subject suggest, I have build a macro that will need a variable input
Sub GetFile(Account as String)
Currently i am setting multiple sub to call the script and assign them to different command buttons
Sub AC1_File
Call GetFile("Account1")
end sub
Sub AC2_File
Call GetFile("Account2")
end sub
And the list go on
I am trying to not make my code too long (as i got double digits accounts),
is it possible for me code to get properties of the commandbutton name and use it instead of Account1,2,3...?
Something like below?
Call GetFile(triggering-commandbutton.name)

Form Controls
In a normal module add a procedure with no arguments:
Public Sub Button_Click()
GetFile Application.Caller
End Sub
This code will pick up the button name and pass it to the GetFile procedure.
Sub GetFile(Account As String)
MsgBox "Account Name is " & Account
End Sub
So now all you need to do is name your buttons Account1, Account2, etc..
ActiveX Controls
If you're using ActiveX controls you can use a class to capture the click event.
Create a class module and name it clsButtonClick.
Add this code to the class module:
Public WithEvents AccountBtn As MSForms.CommandButton
Private Sub AccountBtn_Click()
MsgBox AccountBtn.Name & " on " & AccountBtn.Parent.Name
GetFile AccountBtn.Name
End Sub
At the very top of a normal module add this line:
Public colBtns As New Collection
And add this code to the module:
Public Sub Initialize_Buttons()
Dim wrkSht As Worksheet
Dim btnEvnt As clsButtonClick
Dim obj As OLEObject
For Each wrkSht In ThisWorkbook.Worksheets
For Each obj In wrkSht.OLEObjects
If TypeName(obj.Object) = "CommandButton" Then
Set btnEvnt = New clsButtonClick
Set btnEvnt.AccountBtn = obj.Object
colBtns.Add btnEvnt
End If
Next obj
Next wrkSht
End Sub
This will go through each sheet in your workbook and give any ActiveX command buttons the click event from the class module.
Update the Initialize_Buttons procedure if you need to limit it to a specific sheet, or specific buttons on a sheet.
Finally call the Initialize_Buttons code in the Workbook_Open event in the ThisWorkbook module.

You can create many commandbuttons as ActiveX controller, then write VBA like below:
Private Sub CommandButton1_Click()
Call GetFile("Account1")
End Sub
Private Sub CommandButton2_Click()
Call GetFile("Account2")
End Sub

Related

How can I manually trigger the Activate event of a worksheet in VBA?

I have a worksheet with:
Private Sub Worksheet_Activate()
MsgBox "Ran"
End Sub
I have a button on my toolbar that I made. What I want it to do is trigger this method on the currently selected WorkSheet.
I figured I could do Call ActiveWorksheet.Activate or Call Worksheet.Activate but while these seem to execute without errors, the method is not called.
As a workaround I considered adding a public DoActivate method, but it seems a bit lame and I would likely have to fiddle with CallByName to get it to work (and developers would have to remember to implement this method on every worksheet).
Is there a reason why my Activate method is not calling manually via the above code, or a suitable workaround to get what I'm looking for?
Move your code to a new Sub called OnActivate
Private Sub Worksheet_Activate()
OnActivate
End Sub
Private Sub OnActivate() 'or Public if you call from another module
MsgBox "Ran"
End Sub
The Worksheet_Activate() event handler can be called manually from inside the module by Worksheet_Activate like any other sub (although this is IMO not a nice way to do it)
If you want to ensure all worksheets have the same method, then you can make them Implement an interface: e.g.
Class module: IActivateHandler
Public Sub OnActivate()
End Sub
Then in Sheet1, 2, 3 etc:
Implements IActivateHandler
Private Sub IActivateHandler_OnActivate()
MeOnActivate
End Sub
Private Sub Worksheet_Activate()
MeOnActivate
End Sub
Private Sub MeOnActivate()
MsgBox "Ran"
End Sub
And the button:
Private Sub Button1_Click()
Dim sheetToCall As IActivateHandler
' Debug.Assert TypeOf ActiveSheet Is IActivateHandler
Set sheetToCall = ActiveSheet 'gets the IActivateHandler of the sheet, ensuring it is defined. Will error if it isn't
sheetToCall.OnActivate 'runs the IActivateHandler_OnActivate() method of sheet1
End Sub
You can call the activating event of any active sheet (without knowing its name) in this way:
Create the next event in ThisWorkbook code module. Or, simple copy the following code. Take care that such an event does not already exist:
Public Sub Workbook_SheetActivate(ByVal Sh As Object)
MsgBox Sh.Name & " activated..."
'the necessary code here...
End Sub
Then, call it from a standard module in the next way:
ThisWorkbook.Workbook_SheetActivate ActiveSheet
If you want excepting some sheets, you can adapt the event code to do it:
If sh.Name <> "MySheetName" then
MsgBox Sh.Name & " activated..."
'the necessary code here...
End if
If many sheets should be excepted, an array of sheet names should be built and use Application.Match to differentiate between the sheets to use their event and the other ones.
Edited:
If you need a piece of code written in an add-in (or any macro enabled workbook), able to catch the Activate event of a sheet in any (other) open workbook, you should proceed in the next way:
Copy the next declaration on top of the add-in ThisWorkbook code module (in the declarations area):
Public WithEvents appEvHandler As Application
In the same code module, copy the next code:
Private Sub appEvHandler_SheetActivate(ByVal sh As Object)
If sh.Parent.Name <> ThisWorkbook.Name Then
MsgBox sh.Parent.Name & " workbook, sheet " & sh.Name & " activated..."
Else
Debug.Print "changed in this workbook..."
End If
End Sub
Copy also the next Sub, which will activate the event:
Sub activateAppEvHandler()
Set appEvHandler = Application 'It can be placed in `Workbook_Open` event to be run when workbook opens
End Sub
If you want to inactivate it (for some reason...), use the next Sub:
Sub InactivateAppEvHandler()
Set appEvHandler = Nothing
End Sub
Please, test it and send some feedback. I must confess I am not sure I correctly understood what you need. I was asking for a scenario to be followed, but I tried imagining that this is what you want...

Get the last deactivated worksheet

Private Sub Worksheet_Deactivate()
Msgbox(worksheet.Name)
End Sub
How can I get the last deactivated Sheet once I press on any sheet other than the sheet of interest.
You firstly create a Public variable on top of ThisWorkbook code module (in the declarations area):
Public lastSheetName As String
Put the next code in the Workbook_SheetDeactivate event (also in ThisWorkbook code module):
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
lastSheetName = Sh.name
End Sub
Then you can return the name of the last deactivated sheet with a simple Sub or inside another event code. Try pasting the next code in a standard module and run it. Of course, after you deactivated at least a sheet...
Sub LastDeactivatedSheet()
MsgBox ThisWorkbook.lastSheetName
End Sub
3.a Or put the same code in the Workbook_SheetActivate event , in this way:
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
MsgBox "You are coming from " & ThisWorkbook.lastSheetName
End Sub
Each time you activate another sheet, it will inform you from which sheet you come...

Call same SUB from multiple buttons in VBA

I have multiple buttons (active x) on a spreadhseet in same column but different rows. These buttons capture the start time of an activity.
If button 1 is pressed cell next to it should be populated by current time.
If button 2 is pressed cell next to it should be populated by current time. and so on.....
I have written a SUB in VBA as follows:
Private Sub StartTimer_Click()
Range("I4").Value = Now
End Sub
I do not want to repeat this code for each button action. Please let me know how it can be made dynamic.
A simple WithEvents example:
in a class (named clsButtons):
Private WithEvents Bt As MSForms.CommandButton
Property Set obj(b As MSForms.CommandButton)
Set Bt = b
End Property
Private Sub Bt_Click()
'uses the right of the name of the CommandButton
Cells(1 + Right(Bt.Name, 1) * 3, 9).Value = Now
End Sub
In the sheetcode (the one with the buttons):
Dim myButtons As Collection
Private Sub Worksheet_Activate()
Dim ctl As OLEObject
Dim ButtonClass As clsButtons
Set myButtons = New Collection
For Each ctl In Sheet1.OLEObjects
If ctl.progID = "Forms.CommandButton.1" Then
Set ButtonClass = New clsButtons
Set ButtonClass.obj = ctl.Object
myButtons.Add ButtonClass
End If
Next ctl
End Sub
Create a standard module and put the procedure in there.
While it is possible to share a procedure in a private module, it's best practice to put any shared procedures in a shared module.
In the VBA Editor click Insert > Module,
Paste into there, and give it a unique name. Using your example you could do something like:
Public Sub SetTimeValue()
Range("I4").Value = Now
End Sub
...then call this public stub from your other one, like:
Private Sub StartTimer_Click()
SetTimeValue
End Sub
...and from any other locations where you need to call your code.
I assume that you have more than one line of code for the actual procedure you're concerned about, otherwise copying it repeatedly isn't really a concern.
More Information:
MSDN : Understanding Scope and Visibility
Office Support : Scope of variables in Visual Basic for Applications
Chip Pearson : Understanding Scope Of Variables And Procedures
PowerSpreadsheets : Excel VBA Sub Procedures: The Complete Tutorial
MVP : Cut out repetition using subs and functions with arguments

Calling a userform in Excel VBA and continue depending on which button was clicked

I have four modules, three buttons and one userform, a progressbar, in my Excel workbook. I would like to show a progressbar during the runtime of all four modules.
Example:
I click on a button which executes the following code and makes my progressbar visible:
Private Sub GWPCClearDataButton_Click()
ProgressBar.Show
End Sub
In my userform i have the following code:
Private Sub UserForm_Activate()
GWPCClearData
End Sub
This calls one of my four modules which works fine so far.
Now here's where I'm stuck.
Of course, I would like to use the same progressbar for all modules but how can I determine in the userform code block which button was clicked and then depending on that call another module?
Example:
Private Sub GWPCClearDataButton_Click()
ProgressBar.Show
End Sub
Private Sub GSEPClearDataButton_Click()
ProgressBar.Show
End Sub
UserForm:
Private Sub UserForm_Activate()
If "BUTTON_NAME" = "GWPCClearDataButton" Then
GWPCClearData
ElseIf "BUTTON_NAME" = "GSEPClearDataButton" Then
GSEPClearData
End if
End Sub
How could I do that? I have yet to find a possibility to pass a parameter to my userform which would contain the button name.
Thanks for any help.
In your form put
Sub Start_Form(Called_From as string)
'Process Called_From as needed
End Sub
When you call your form just call the sub first like below
<form_name>.Start_Form "Button Called From"
<form_name>.Show
Basically you have to pass the variable via another sub(can be called anything) in the userform and then show the form after
User Form Code
Dim test
Private Sub UserForm_Activate()
MsgBox test
End Sub
Sub start(tt)
test = tt
End Sub
Module code
Sub t()
UserForm1.start "Hello World!"
UserForm1.Show
End Sub

Get Selected value of a Combobox

I have a thousands of cells in an Excel worksheet which are ComboBoxes. The user will select one at random and populate it.
How do I get the selected ComboBox value? Is there a way to trigger a function (i.e. an event handler) when the ComboxBoxes has been selected?
You can use the below change event to which will trigger when the combobox value will change.
Private Sub ComboBox1_Change()
'your code here
End Sub
Also you can get the selected value using below
ComboBox1.Value
If you're dealing with Data Validation lists, you can use the Worksheet_Change event. Right click on the sheet with the data validation and choose View Code. Then type in this:
Private Sub Worksheet_Change(ByVal Target As Range)
MsgBox Target.Value
End Sub
If you're dealing with ActiveX comboboxes, it's a little more complicated. You need to create a custom class module to hook up the events. First, create a class module named CComboEvent and put this code in it.
Public WithEvents Cbx As MSForms.ComboBox
Private Sub Cbx_Change()
MsgBox Cbx.Value
End Sub
Next, create another class module named CComboEvents. This will hold all of our CComboEvent instances and keep them in scope. Put this code in CComboEvents.
Private mcolComboEvents As Collection
Private Sub Class_Initialize()
Set mcolComboEvents = New Collection
End Sub
Private Sub Class_Terminate()
Set mcolComboEvents = Nothing
End Sub
Public Sub Add(clsComboEvent As CComboEvent)
mcolComboEvents.Add clsComboEvent, clsComboEvent.Cbx.Name
End Sub
Finally, create a standard module (not a class module). You'll need code to put all of your comboboxes into the class modules. You might put this in an Auto_Open procedure so it happens whenever the workbook is opened, but that's up to you.
You'll need a Public variable to hold an instance of CComboEvents. Making it Public will kepp it, and all of its children, in scope. You need them in scope so that the events are triggered. In the procedure, loop through all of the comboboxes, creating a new CComboEvent instance for each one, and adding that to CComboEvents.
Public gclsComboEvents As CComboEvents
Public Sub AddCombox()
Dim oleo As OLEObject
Dim clsComboEvent As CComboEvent
Set gclsComboEvents = New CComboEvents
For Each oleo In Sheet1.OLEObjects
If TypeName(oleo.Object) = "ComboBox" Then
Set clsComboEvent = New CComboEvent
Set clsComboEvent.Cbx = oleo.Object
gclsComboEvents.Add clsComboEvent
End If
Next oleo
End Sub
Now, whenever a combobox is changed, the event will fire and, in this example, a message box will show.
You can see an example at https://www.dropbox.com/s/sfj4kyzolfy03qe/ComboboxEvents.xlsm
A simpler way to get the selected value from a ComboBox control is:
Private Sub myComboBox_Change()
msgbox "You selected: " + myComboBox.SelText
End Sub
Maybe you'll be able to set the event handlers programmatically, using something like (pseudocode)
sub myhandler(eventsource)
process(eventsource.value)
end sub
for each cell
cell.setEventHandler(myHandler)
But i dont know the syntax for achieving this in VB/VBA, or if is even possible.

Resources