![](/img/trans.png)
[英]UserForm variable scope: transfer 2D array values from userform2 to userform1
[英]It is possible to access a dynamic object of Excel UserForm1 from code of UserForm2? Not from code of a module
我有一個“類”模塊,我的動態標簽聲明和事件
Option Explicit
Public WithEvents ClassLabel As MSForms.Label
Public Sub ClassLabel_Click()
If InStr(ClassLabel.Name, "LB_Label") Then
Set CurrentLabel = ClassLabel
'Bla Bla Bla
End If
End Sub
我在 UserForm1 的“FR_Runtime”框架中創建了 15 個動態標簽,我將它們保存在一個普通 Module1 的 Controls_Init() Sub 的數組中,如下所示
Option Explicit
Public gArrayClassLabel() As New Class
Public CurrentLabel As MSForms.Label
Public Sub Controls_Init()
Dim Row As Integer
Dim nRow As Integer
Dim H As Integer
Dim LB_Label As MSForms.Label
nRow = 15
H = 30
ReDim gArrayClassLabel(1 To nRow)
For Row = 1 To nRow
Set LB_Label = UserForm1.FR_Runtime.Controls.Add("Forms.Label.1")
With LB_Label
.Name = "LB_Label" & Row
.Caption = " Label " & Row & ", 2"
.Left = 100
.Top = H
.Width = 75
.Height = 18
.ForeColor = vbRed
.BackColor = vbWindowBackground
.BorderStyle = fmBorderStyleSingle
.SpecialEffect = fmSpecialEffectSunken
End With
Set gArrayClassLabel(Row).ClassLabel = LB_Label
H = H + 30
Next Row
End Sub
從我的 UserForm1.FR_Runtime_Exit() 事件(或任何其他 UserForm1、Module1 代碼)中,我可以訪問第五個動態 label,如下所示
Private Sub FR_Runtime_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Set glbCurrentLabel = gArrayClassLabel(5).ClassLabel
With UserForm1.TextBox1
.Text = Trim$(glbCurrentLabel.Caption)
.Left = glbCurrentLabel.Left
.Top = glbCurrentLabel.Top
.SelStart = 0
.SelLength = Len(glbCurrentLabel.Caption)
End With
End Sub
從 UserForm2,我可以訪問在設計時創建的 label: UserForm1.Label3.Caption = "This is an design time Label"
我可以從 UserForm2 的 Sub 訪問 gArrayClassLabel(5).ClassLabel 嗎? 不是來自 Module1 代碼。
感謝 Tragamor,我沒有想過 class 模塊屬性。 這是新的“類”模塊
Public WithEvents ClassLabel As MSForms.Label
Private sContent As String
'new Get property
Property Get Content() As String
Content= sContent
End Property
'new Let property
Property Let Content(NumLbl As String)
sContent = gArrayClassLabel(NumLbl).ClassLabel.Caption
End Property
Public Sub ClassLabel_Click()
If InStr(ClassLabel.Name, "LB_Label") Then
Set CurrentLabel = ClassLabel
'Bla Bla Bla
End If
End Sub
我可以從代碼中的任何地方訪問第五個動態label Caption,如下所示
Dim NumDynamicLabel As New Class
'I use Let Content property to obtain the fifth dynamic label Caption
NumDynamicLabel.Content = 5
Dim CaptionDynamicLabel As String
'I use the Get Content Property to retrieve Caption of fifth dynamic label
CaptionDynamicLabel = NumDynamicLabel.Content
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.