我正在尝试使用VBA以编程方式创建类型为MSForms.ListBox
的列表框。
我无法使用Set ListBox = New MSForms.ListBox
来执行此操作,因为它会引发编译错误:Invalid use of the New keyword
。
在下面的代码中,当我在Invalid use of the New keyword
中创建OLEObject
时,它会创建OLEObject
(或其他数字),然后可以在执行结束后在Macro1
中将其分配给类型为VBAProject.Sheet1.ListBox1
的变量但是它仅在我一次运行一个宏的情况下才有效。
然后使用Macro2
,我可以更改MSForms.ListBox
之类的属性(即使我不知道如何更改标头值,除了使用MSForms.ListBox
将列表值寻址到某个范围之外)。
如果我尝试逐步执行代码,则会收到消息ListBox.ColumnHeads = True
。
[我从录制宏和ListBox.ListFillRange = RangeAddress
得到了Can't enter break mode at this time
。
Can't enter break mode at this time
编辑:
使用接受的答案中给出的解决方案的简单工作示例:
OLEObject
[当您在inserting a List Box ActiveX Control代码块中按' Microsoft Excel 2013 built-in references:
' Excel - Microsoft Excel 15.0 Object Library
' VBA - Visual Basic For Applications
' VBA project library:
' VBAProject
' Aditional references:
' MSForms - Microsoft Forms 2.0 Object Library
Private Sub Macro1()
Dim Worksheet As Excel.Worksheet
Dim ListBox As Excel.ListBox
Dim Shape As Excel.Shape
Dim OLEObject As Excel.OLEObject
Set Worksheet = VBAProject.Sheet1
Worksheet.Range("A1").Value = "Header"
Worksheet.Range("A2").Value = "Value 1"
Worksheet.Range("A3").Value = "Value 2"
Worksheet.Range("A4").Value = "Value 3"
For Each Shape In Worksheet.Shapes
Shape.Delete
Next Shape
Set ListBox = Worksheet.ListBoxes.Add(60, 10, 100, 100)
ListBox.List = Array("Header", "Value 1", "Value 2", "Value 3")
ListBox.ListFillRange = "A1:A4"
Set OLEObject = Worksheet.OLEObjects.Add(ClassType:="Forms.ListBox.1", Link:=False, Left:=170, Top:=10, Width:=100, Height:=100)
OLEObject.ListFillRange = "A1:A4"
Set Shape = Worksheet.Shapes.AddOLEObject(ClassType:="Forms.ListBox.1", Link:=False, Left:=280, Top:=10, Width:=100, Height:=100)
End Sub
Private Sub Macro2()
Dim Worksheet As Excel.Worksheet
Dim ListBox As MSForms.ListBox
Set Worksheet = Excel.Application.ActiveSheet
Set ListBox = VBAProject.Sheet1.ListBox1
ListBox.ListFillRange = ""
ListBox.List = Array("Header", "Value 1", "Value 2", "Value 3")
ListBox.ColumnHeads = True
ListBox.ListFillRange = "A1:A4"
ListBox.BorderStyle = MSForms.fmBorderStyle.fmBorderStyleSingle
End Sub
时,您会看到智能感知并没有显示某些属性,例如Private Function CreateListBox( _
Optional ByVal Worksheet As Excel.Worksheet = Nothing, _
Optional ByVal Width As Long = 100, _
Optional ByVal Height As Long = 100, _
Optional ByVal Left As Long = 0, _
Optional ByVal Top As Long = 0 _
) As MSForms.ListBox
Const ClassType As String = "Forms.ListBox.1"
If Worksheet Is Nothing Then
Set Worksheet = Excel.Application.ActiveSheet
End If
Set CreateListBox = Worksheet.OLEObjects.Add( _
ClassType, _
Left:=Left, _
Top:=Top, _
Width:=Width, _
Height:=Height).Object
End Function
Private Sub Test()
Dim ListBox As MSForms.ListBox
Set ListBox = CreateListBox
Stop ' Able to stop/suspend code execution here but not inside the function when creating the OLEObject
End Sub
,.
或With lb...End With
。您可以使用.ColumnHeads
这是您要尝试的吗?
.BorderStyle
在行动
.List