我正在嘗試使用 VBA 中的類將_Change() 事件添加到動態創建的 TextBox 中。但是,當我嘗試運行我的代碼時,什么也沒有發生。你能指出我錯在哪里嗎?
我有類conditionEventClass
Public WithEvents conditionEvent As MSForms.textBox
Public Property Let textBox(boxValue As MSForms.textBox)
Set conditionEvent = boxValue
End Property
Public Sub conditionEvent_Change()
MsgBox conditionEvent.Name & " changed."
End Sub
我的模塊中有以下代碼:
Sub addConditions()
Dim conditionCommand As conditionEventClass
Dim newTextBox As MSForms.textBox
Set newTextBox = commandRequestForm.MultiPage1(1).Controls.Add("Forms.TextBox.1", "conditionValue", True)
With newTextBox
.Name = "conditionValue"
.Left = 750
.height = 15
.Width = 100
.Top = 20
End With
Set conditionCommand = New conditionEventClass
conditionCommand.textBox = newTextBox
End Sub
我希望我的子conditionEvent_Change()將顯示 msgBox。但不幸的是什么也沒有發生。
uj5u.com熱心網友回復:
僅談論一個文本框,您可以使用下一個更簡單的方法:
1.在表單代碼模塊之上(宣告區)宣告一個私有變數:
Private WithEvents myTextBox As MSForms.TextBox
- 然后,為上面宣告的變數創建事件:
Private Sub myTextBox_Change()
MsgBox activecontrol.name & " changed."
End Sub
- 使用您的改編代碼作為:
Sub addConditions()
Dim newTextBox As MSForms.TextBox
Set newTextBox = commandRequestForm.MultiPage1(1).Controls.Add("Forms.TextBox.1", "myTextBox", True)
With newTextBox
.left = 10
.height = 15
.width = 100
.top = 20
End With
Set myTextBox = newTextBox
End Sub
對于 1 到 3、4 這樣的控制元件,您可以使用更簡單(如上所示)的方式。如果您需要即時創建大量此類控制元件,我可以向您展示如何調整您的代碼......
編輯:
請使用下一個作業方式,使用一個類分配給許多動態創建的文本框:
- 復制類模塊中的下一個代碼并將其命名為“clsTBox”:
Option Explicit
Public WithEvents newTBox As MSForms.TextBox
Private Sub newTBox_Change()
MsgBox newTBox.name & " changed."
End Sub
Private2.在表單代碼模塊之上宣告一個變數:
Private TBox() As New clsTBox
- 使用下一步
Sub創建三個文本框并將Click事件分配給它們:
Private Sub CreateThreeTB()
Dim i As Long, txtBox01 As MSForms.TextBox, leftX As Double, tWidth As Double, k As Long
leftX = 20: tWidth = 50
ReDim TBox(100) 'use here the maximum number of text boxes you intend creating
For i = 1 To 3
Set txtBox01 = Me.Controls.Add("Forms.TextBox.1", "dynTxtBox_" & i)
With txtBox01
.top = 10
.left = leftX: leftX = leftX tWidth
.width = tWidth
.Text = "something" & i
End With
Set TBox(k).newTBox = txtBox01: k = k 1
Next i
ReDim Preserve TBox(k - 1)
End Sub
Sub從事件或另一個控制元件呼叫上面的Initialize代碼,使用新創建的文本框值并查看更改事件是如何觸發的...
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/533427.html
標籤:擅长vba用户表单
