【问题标题】:How to trigger a Form from a Macro and get the inputs from a Form into VBA Module Code如何从宏触发表单并将表单中的输入获取到 VBA 模块代码中
【发布时间】:2021-12-31 18:36:28
【问题描述】:

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

表格内的代码如下:

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

感谢您的帮助!!

【问题讨论】:

    标签: excel vba userform


    【解决方案1】:

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

    您的表单代码

    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 是我喜欢使用的名称。你可以给他们起你喜欢的名字。

    【讨论】:

    • 我是否需要为每个按钮选择提供单独的代码,例如模块代码中的“YTD”和“特定功能”?还是我需要使用一些 IF 条件来获得正确的字符串?
    • 您打算如何在原始代码中使用InputMsg
    • 我想把它当作字符串,比如如果 InputMsg 是“YTD”,则使用此过程,如果是“特定功能”,则必须使用其他过程。
    • 我刚拿到这个!!谢谢...让我试试它是否正常工作! :)
    • If ChartType = "YTD" Then 同样是ElseIf ChartType = "Specific Months" Then
    猜你喜欢
    • 1970-01-01
    • 2012-05-06
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 2013-12-11
    • 1970-01-01
    • 2020-03-08
    相关资源
    最近更新 更多