如何调用模块以从 Sub_Click 执行脚本?

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

我的 sheet 中有 10 个宏按钮。 我有一个带有客户报告脚本的模块。

当从 sheet 单击按钮 1 时,我创建了一个名为 Button1_Click() 的新宏。在这个脚本中,我只想设置一个变量,Row1:

Button1_Click()
Dim Row1 As Integer
Row1 = 1

从这里我想调用包含完整报告脚本的模块 CustomerReport,并且我想在 CustomerReport 脚本中重新使用 Row1 值,因为它标识了客户 1。

我已经尝试 Call CustomerReport 但没有任何反应。我该如何解决?

你可以这样传递东西:

Sub CallingSub()
    Dim Row1 as Long
    Row1 = 1
    Call CalledSub(Row1)
End Sub

Sub CalledSub(Row1 as Long)
    msgbox "Row1 = " & Row1
End Sub

你也可以这样缩短:

Sub CallingSub()
    Call CalledSub(1) '<-- Putting the 1 in here is fine and the type is not passed anyway, notice in CalledSub we define it as a long within the brackets
End Sub

Sub CalledSub(Row1 as Long)
    msgbox "Row1 = " & Row1
End Sub

丹在那里找到了答案。除此之外,您还可以像这样跨模块调用方法和函数:

模块 1:

Sub Test1()
    MsgBox "Module1 test1"
End Sub

Function GetNewPay(Pay As Integer, RaisePercent As Double) As Double
    GetNewPay = Pay * (1 + (RaisePercent / 100))
End Function

模块 2:

Sub Test1()
    MsgBox "Module2 test1"
    Call Module1.Test1
    Call Test2("Just testing")

    Dim NewPay As Double, OldPay As Integer, RaisePercent As Double
    OldPay = 20000
    RaisePercent = 15
    NewPay = Module1.GetNewPay(OldPay, RaisePercent)

    MsgBox "Old Pay is " & OldPay & ". New pay is " & NewPay & " with " & RaisePercent & "% raise"

End Sub

Sub Test2(Message As String)
    MsgBox "Message is " & Message & " from module2 test1"
End Sub

放入模块 1 Public Row1 as Integer...

在你的子里 Row1 = 1

Row1 将是 1 只要您不更改它,重新加载工作簿或重置您的宏...这样您就可以将其设置为任何值而无需调用另一个宏...但您仍然可以使用该值后来:)

编辑: 仅供您评论

创建宏时最好使用标准集模式:
首先设置特殊行为,如

Option Explicit
...

随心所欲

然后根据需要声明所有全局变量和类型 (从类型开始,根据它们声明全局变量)

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

Public dRunner() As Variant
Public MySuperVariable As MyType
...

在第三部分把你需要的所有直接函数(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
...

那么都是自创函数

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

然后从你的潜艇开始......除了Option Explicit你不会使用其中的大部分......但是,只要保持顺序就可以省去很多麻烦:)