这是我的代码的开头:
Private FilesPath As String
Private CostCentersPath As String
Private FinalPath As String
Private CurrentName As String
Private CostCenters As Worksheet
Private Final As Workbook
Private Template As Worksheet
Sub ReadySetGo()
FilesPath = "O:\MAP\04_Operational Finance\Accruals\Accruals_Swiss_booked\2017\Month End\10_2017\Advertising\automation\" 'path change ("automation")
CostCentersPath = FilesPath & "CostCenters.xlsx"
CurrentName = InputBox("Please adjust the final file name:", , "ABGR_2017-10_FINAL.xls.xlsx")
FinalPath = FilesPath & CurrentName
Set CostCenters = Workbooks("CostCenters.xlsx").Worksheets("Cost Center Overview")
Set Final = Workbooks(CurrentName)
Set Template = Workbooks("Template.xlsm").Worksheets("Template")
End Sub
Sub ReadySetGo仅用于为变量赋值,并从模块中的其他子中调用。但很明显,通过这种方法,每次调用sub时都会弹出输入框。 除了Workbook.Open事件之外,还有其他方法可以将变量的CurrentName值传递给模块中的其他subs,以避免多个InputBox?
谢谢, 鲍尔泰克
答案 0 :(得分:2)
一般而言,根据您的应用程序的确定方式,有很多很好的方法可以做您想做的事情。 可能最简单的就是写:
If CurrentName <> vbNullString Then
InputBox("Please adjust the final file name:", , "ABGR_2017-10_FINAL.xls.xlsx")
End if
但要小心,因为它可能会破坏你的代码。但是,在最好的情况下,您只能运行一次。
另一种方法是将CurrentName
值保存在给定范围内,并且每次都从那里读取它:
If Len(Range("A1")) = 0 Then
Range("A1") = InputBox("Please ...")
End if
CurrentName = Range("A1")
通常,您可以更进一步,将单例模式引入代码https://en.wikipedia.org/wiki/Singleton_pattern,从而确保CurrentName
仅分配一次。但是,在这种情况下可能有点矫枉过正 - How to create common/shared instance in vba
答案 1 :(得分:1)
Vityata给出了很好的答案,我会将CurrentName声明为公共变量但是如果我必须在相同的设置中进行,那么
Static CurrentName As String
Static HasName As Boolean
If Not HasName Then
CurrentName = InputBox("Please adjust the final file name:", , "ABGR_2017-10_FINAL.xls.xlsx")
HasName = True
End If