Putting common command button code in ThisWorkbook - vba

After moving command button code into the ThisWorkbook area as opposed to the individual sheet it doesn't appear to get called. Is there a reason for this, is there some way I can have the same code called from multiple buttons each on different worksheets?

The command button is a worksheet object, not a workbook object.
With this being said, you can reuse the code by keeping the command button in your worksheet's object, but place the main code in a standard module (keep it away from your workbook's module).
This would be in a standard module:
Sub mainCode(ws As Worksheet)
'Your Code
End Sub
This would be in your Worksheet's private module:
Private Sub CommandButton1_Click()
mainCode ws 'make a call to the code above
End Sub

Related

Private Sub App_SheetChange Doesnt work if an error occurs in a previous macro

I have the following code to activate a macro when a change is made to cell A1
Class Module
Option Explicit
Private WithEvents App As Application
Private Sub Class_Initialize()
Set App = Application
End Sub
Private Sub App_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Sh.Name = "S" Then
Dim rngKeyCells As Range
Set rngKeyCells = Sh.Range("A1")
If Intersect(rngKeyCells, Target) Is Nothing Then
Exit Sub
End If
Application.Run "a"
End If
End Sub
This_Workbook Code
Private OurEventHandler As EventHandler
Private Sub Workbook_Open()
'Initiates the data change when the filter is changed
Set OurEventHandler = New EventHandler
End Sub
This works absolutely fine usually, however an issue occurs if i try making a change in A1 after i open VBA.
It will work fine 90% of the time but if during one of the previous macro's that i run, there is an error, it won't work.
Example - I run a macro that deletes the Worksheet to the left of the active one. If there is no worksheet to the left of the active one it will error. I press end and that's fine. Now if i try to change the cells A1 and expect the macro above to run, nothing happens.
Is this the kind of thing that is solvable without showing the entire macro? Or could it be something that is inbuilt into the rest of the macro that is causing the issue?
Thanks
In the programming there is something named Design Patterns. In your case, it would be really useful to make a Singleton for the App variable.
Here is a good example of it for VBA:
How to create common/shared instance in vba
As already mentioned in the comments: When an error happens and end is pressed, the whole VBA-Context is reset, the content of global Vars is lost (so your variable OurEventHandler is nothing).
If you can't catch all errors to ensure that this reset isn't happening (and I think you never really can), maybe it is easiest to implement the event handler in the worksheet itself:
Private Sub Worksheet_Change(ByVal Target As Range)
' Ne need to check Worksheet as the Hander is valid only for the Worksheet
if target.row = 1 and target.column = 1 then
Application.Run "AIMS_and_eFEAS_Report.AIMS_Criteria"
end if
End Sub

Unable to load userform

I am unable to load an userform on opening workbook. Object is Workbook, procedure is Open and have this code in ThisWorkbook.
Private Sub Workbook_Open()
frmWelcome.Show
End Sub
Here's some code that I use, placed in a module called mMain with the form called fForm. I suggest that you start fresh, with something like this, make sure that works, and proceed from there, changing one thing at a time.
Option Explicit
Public dLog As fForm
Sub main()
Set dLog = New fForm
dLog.Show vbModeless 'doesn't have to be modeless
End Sub

Userform not triggering Initialize or Activate event

I kept a userform control button in my worksheet to fire up a macro, which in turn shows a user form, In the form I wish to display the opened files in checkboxes(using the Workbooks collection).I wish to run a macro that performs action for the user selected files only.
So for the button in my worksheet, I have assigned the following macro
Private Sub Button2_Click()
Load MyForm
MyForm.Show
End Sub
At first I kept the below code in the module where my macro sub is there.Since it's not working, I right clicked on user form and selected view code and kept the below code there.But still it's showing the same static designed user form, not the dynamic.I kept breakpoint at both load Myform and MYform.Show() and I stepped through code.It never went into intialize or activate method at all.
Private Sub MyForm_Activate()
'for checking the whether this method is called or not I am trying to change caption
MyForm.LabelSelectFile.Caption = "dhfdfldkfldzjf;zdfkz;d"
Dim mymyWorkBook As Workbook
For Each mymyWorkBook In Workbooks
'code for creating checkbox based on the file name displayed by the workbook collection
Next mymyWorkBook
End Sub
I can't understand why that event is not getting triggered.Please help me to overcome this.Thanks in advance
Even though the name of the form is MyForm, you still need to use userform.
'~~> in your worksheet
Private Sub Button2_Click()
MyForm.Show
End Sub
'~~> In the userform code area
Private Sub UserForm_Initialize()
'~~> Your code here
End Sub
or
Private Sub UserForm_Activate()
End Sub
The best is to always select the event from the drop down, rather than typing it

Dynamically Running VBA code when sheet changes

Is there a way in which I can get a sub in VBA to run whenever the user changes the sheet. Basically, what I am looking to do is hide all of the sheets besides the one that the user is on.
Thanks!
Given all the sheets other than the one you are leaving and the one you are going to will be hidden, then you can address directly just the sheet you are exiting with this Workbook level event (goes in ThisWorkbok)
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
Sh.Visible = False
End Sub
You can use the following event, placed in the Workbook code module:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Call _Your_Macro_Name_
End Sub
Replace _Your_Macro_Name_ with the name of the subroutine that you want to execute.

Excel VBA - Assign value from UserForm ComboBox to Global Variable

I have a userform with a basic combobox and command button. When the user hits the command button, I want the UserForm to close, and the value of the combobox to be saved in a variable that can be accessed by a subroutine contained within "ThisWorkbook".
In the UserForm code:
Public employee_position As String
Public Sub CommandButton1_Click()
employee_position = Me.ComboBox1.Value
Unload Me
End Sub
In the "ThisWorkbook" Code
Private Sub GetUserFormValue()
Call Userform_Initialize
EmployeePosition.Show
MsgBox employee_position
End Sub
When "GetUserFormValue()" runs, the UserForm comes up, you can select a value in the combobox and press the command button, but when the MsgBox comes up, it displays "" (Nothing)
What am I doing wrong here?
When you Unload Me, I think you lose all information associated with the module (including the global variable). But if you use Me.Hide rather than Me.Unload, then you can access the value of the form after the routine returns. So try this:
-- userform code includes:
Public Sub CommandButton1_Click()
Me.Hide
End Sub
-- main module includes:
Private Sub GetUserFormValue()
Call Userform_Initialize
EmployeePosition.Show
MsgBox EmployeePosition.ComboBox1.Value
Unload EmployeePosition
End Sub
I think that should work.
I had the same problem, and this is how I resolved it:
If the main code is in a worksheet, and the variable is declared as public in that worksheet (e.g. in Microsoft Excel Objects -> Sheet1 (Sheet1)), the result from "Unload Me" cannot be passed from a UserForm to the worksheet code.
So to solve my problem, I inserted a new Module, and declared my public variable there. I didn't even have to move my code from the worksheet to the module... just the declaration of the public variable.
I hope this works for you too!
Andrew