我目前正在开展一个项目,我将选择最多 5 个项目进行比较,结果显示在最多 5x5 的动态网格中。我的目标是让这个网格由命令按钮组成,这样每个按钮的标题是行和列项目之间的百分比相似度,并且在单击按钮时,将显示行和列项目之间的共同单位在一个消息框中。
我或多或少知道如何生成实际的按钮数组。但是,我读到的所有内容都表明我需要创建一个类来处理按钮单击,因为我不想制作 20 个子程序,它们都具有相同的代码。我无法让这个类正常工作,我可以使用一些技巧。这是我到目前为止所拥有的。
在名为 DynButton 的类模块中:
Public Withevents CBevents as MSForms.CommandButton
Private Sub CBevents_Click()
DisplayOverlappedUnits 'Sub that will display the units that are the same
'between items i and j- may use Application.Caller
End Sub
在用户表单本身中:
Private Sub Userform_Initialize()
Dim NumItems as integer
Dim ComparisonArray() as DynButton
Dim ctlButton as MSForms.CommandButton
'QuestionList() is a public type that stores various attributes of the
'items I'm comparing.
'This code determines how many items were selected for comparison
'and resets the item array accordingly.
NumItems=0
For i=1 to 5
If QuestionList(i).Length>0 Then
NumItems=Numitems+1
QuestionList(NumItems)=QuestionList(i)
End If
Next
Redim ComparisonArray(1 to NumItems, 1 to NumItems)
For i = 1 to NumItems
For j=1 to NumItems
Set ctlButton=Me.Controls.Add("Forms.CommandButton.1", Cstr(i) & Cstr(j) & cb)
With ctlButton
.Height= CB_HEIGHT 'These are public constants defined elsewhere.
.Width= CB_WIDTH
.Top= TOP_OFFSET + (i * (CB_HEIGHT+ V_PADDING))
If i = j Then .visible = False
.Caption= CalculateOverlap(i,j) 'Runs a sub that calculates the overlap between items i and j
End With
Set ComparisonArray(i,j).CBevents = ctlButton
Next
Next
End Sub
目前,当我点击 Set ComparisonArray 行时,我得到一个“未设置对象或块变量”,我被困住了。我只是在类模块中遗漏了一些东西吗?在此先感谢您的帮助。
编辑添加:我尝试在本文的部分内容中对类代码进行建模,但我还没有让它工作。http://www.siddharthout.com/index.php/2018/01/15/vba-control-arrays/