如何从宏触发表单并将表单的输入获取到 VBA 模块代码

How to trigger a Form from a Macro and get the inputs from a Form into VBA Module Code

我有一个宏,我想在其中为消息框创建自定义按钮,我想触发一个看起来像带有“YTD”、“特定月份”等选项的 Msgbox 的表单。这是我创建的以下表格:

表格内的代码如下:

Option Explicit
Public InputMsg As String

Public Sub CommandButton1_Click()
InputMsg = "YTD"

End Sub

Public Sub CommandButton2_Click()
InputMsg = "Specific Months"

我想将这些输入值获取到我在下面提到的模块代码中:

Sub Chts_Functions_UB()

'CallingForms
On Error Resume Next
Application.DisplayAlerts = False
Set Wb = ThisWorkbook
Set WsCharts = Wb.Sheets("Trend Charts")
Set UBMainChart = WsCharts.ChartObjects("UBMainChart")
Set UBMonthlyYTDSht = Wb.Worksheets("UM - Monthly & YTD")
Set FPFAChart = WsCharts.ChartObjects("FP_FA_YTD Chart")
Set FPBPChart = WsCharts.ChartObjects("FP_BP_YTD Chart")
Set FPRMDChart = WsCharts.ChartObjects("FP_RMD_YTD Chart")
Set FPMonthlyYTDSht = Wb.Worksheets("FP - Monthly & YTD")
YearValue = WsCharts.Range("A1").Value
'btnFunctionName = WsCharts.Shapes(Application.Caller).Name
WsCharts.Range("F2").Value = btnFunctionName

Dim Crows As Long, Ccols As Long
Dim NamedRng As Variant
'****Here I would like to get the Input from the Form (YTD or Specific Months Button)***
Crows = UBMonthlyYTDSht.Range("A" & Rows.Count).End(xlUp).Row
Ccols = UBMonthlyYTDSht.Cells(1, Columns.Count).End(xlToLeft).Column
On Error GoTo 0

感谢您的帮助!!

避免使用 public 变量,除非绝对必要。如下所示将相关值作为参数传递。

您的表单代码

Private Sub CommandButton1_Click()
    Chts_Functions_UB "YTD"
End Sub

Private Sub CommandButton2_Click()
    Chts_Functions_UB "Specific Months"
End Sub

您的模块代码

Sub Chts_Functions_UB(ChartType As String)
    '
    ' Chts_Functions_UB code here
    '
End Sub

也避免使用On Error Resume Next。明智地使用它并使用适当的错误处理。例如

Sub Chts_Functions_UB(ChartType As String)
    On Error GoTo Whoa
    
    Application.DisplayAlerts = False

    '
    ' Chts_Functions_UB code here
    '
    
LetsContinue:
    Application.DisplayAlerts = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

注意LetsContinueWhoa是我喜欢用的名字。你可以给他们起你喜欢的名字。