如何使用VBA在不同的工作簿中使用Userform全局variables值
我已经在不同的文件夹中维护了两个excel工作簿,在第一个excel中,我创build了一个UserForm,里面有两个combobox,我在Userform中声明了一个全局variables“EpcName”,这个全局variables存储了第二个combobox的select值。 现在我的问题是我怎么可以使用Userform中的全局variables的值到其他工作簿,这是在不同的文件夹中。
工作簿1path(在哪里我创build了用户窗体)C:\ Users \ inkapb \ AppData \ Local \ Temp \ EPC AutoTool \ Start Screen -UI \ UI.xlsm
工作簿2pathC:\ Users \ inkapb \ AppData \ Local \ Temp \ EPC AutoTool \ Projects \ Power Plant \ Power Plant EPC 1.xlsm
这里是我写在用户窗体中的代码
Public EpcName As String Private Sub CommandButton1_Click() Dim wb As Workbook Dim ws As Worksheet Set wb = Workbooks("UI.xlsm") Set ws = wb.Worksheets("Sheet2") Dim qwerty As String Dim cf As Range EpcName = Me.ComboBox2.Text 'Want to pass this String to other workbook With ws .Activate With .Range("C1:C10000") Set cf = .Find(what:=EpcName, _ lookat:=xlPart, searchorder:=xlByRows, searchdirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If cf = "" Then MsgBox "nothing" Else Range(cf.Address).Select Selection.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True End If End With End With End Sub
任何帮助表示赞赏。
这应该是可能的。 声明和初始化包含用户表单的工作簿中的variables,例如像这样。
Option Explicit Public EpcName As String Private m_theOtherWorkbook As Workbook Private Sub UserForm_Initialize() On Error GoTo ErrInit Set m_theOtherWorkbook = Workbooks("Power Plant EPC 1.xlsm") Exit Sub ErrInit: MsgBox "Error in " & Me.Name & ". UserForm_Initialize. " & Err.Description, vbCritical, "Error" End Sub
然后在另一个工作簿,类模块ThisWorkbook,添加像这样的公共属性(可能只是一个公共variables)。
Option Explicit Private m_epcName As String Public Property Get EpcName() As String EpcName = m_epcName End Property Public Property Let EpcName(ByVal vNewValue As String) m_epcName = vNewValue End Property
而在用户窗体的代码中,只需调用其他工作簿的EpcName属性(其他工作簿必须打开)。 属性EpcName现在是其他工作簿的新界面的一部分,它应该工作得很好。 HTH
EpcName = "Want to pass this String to other workbook" ' Me.ComboBox2.Text If Not m_theOtherWorkbook Is Nothing Then _ m_theOtherWorkbook.EpcName = EpcName