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

时间:2015-11-01 23:14:43

标签: excel vba excel-vba call

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

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

               0
2015-07-19  ...
2015-08-19  ...
2015-09-19  ...

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

我试过Button1_Click() Dim Row1 As Integer Row1 = 1 但没有任何反应。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

你可以传递这样的东西:

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 :(得分:1)

丹在那里得到了答案。除此之外,您还可以跨模块调用方法和函数,如下所示:

模块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

单词数:

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

答案 2 :(得分:1)

放入Module1 Public Row1 as Integer ...

在你的Sub 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你不会使用大部分......但是,保持订单可以节省很多麻烦:)