Search code examples
vbaexcelcall

How do I call a Module to execute a script from a Sub_Click?


I have 10 macro buttons in my sheet. I have a Module with a script for a Customer Report.

When button 1 is clicked from the sheet I have created a new macro called Button1_Click(). Inside this script I only would like to set one variable, Row1:

Button1_Click()
Dim Row1 As Integer
Row1 = 1

From here I want to call the module CustomerReport that contain the full reporting script, and I want to re-use the Row1 value inside CustomerReport script as it identifies Customer 1.

I have tried Call CustomerReport but nothing happens. How do I solve this?


Solution

  • Put in Module1 Public Row1 as Integer...

    In your Sub just Row1 = 1

    Row1 will be 1 as Long as you dont change it, reload the workbook or reset your macros... this way you can set it to any value without calling another macro... but you can still use the value later :)

    Edit: just for your comment

    when crating macros you best work with the standart set pattern:
    first set special behaviors like

    Option Explicit
    ...
    

    as you need it

    then declare all global variables and types as you need them (start with types to declare global variables based on them)

    Type MyType
      FirstChild As Long
      SecondChild(0 To 20) As Byte
      ThirdChild As String
      ...
    End Type
    
    Public dRunner() As Variant
    Public MySuperVariable As MyType
    ...
    

    in the third part put all direct functions you need (api)

    Public Declare Function SetTimer Lib "user32" (ByVal HWnd As Long, ByVal nIDEvent As Long, ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
    Public Declare Function KillTimer Lib "user32" (ByVal HWnd As Long, ByVal nIDEvent As Long) As Long
    ...
    

    then all self-created functions

    Public Function MyModulo(a As Double, b As Double) As Double
      Do Until a < b
        a = a - b
      Loop
      MyModulo = a
    End Function
    ...
    

    and then start with your subs... except for Option Explicit you wont use most of them... however, just keeping the order saves a lot of trouble :)