gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:22:10 25 4
gpt4 key购买 nike

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

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

关于excel - 如何从宏触发表单并将表单中的输入获取到 VBA 模块代码中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70061055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com