我是初学程序员,正在为我的高级顶点项目制作VBA宏。我正在尝试使用“A列”中的数据填充列表框。它必须是动态的,因为用户将编辑数据。我知道它对于经验丰富的编码器很简单,但我的语法有问题。任何帮助是极大的赞赏!
Private Sub UserForm_Initialize()
Dim LastRowControllers, LastRowBrakes As Integer
Dim Brakes, Controllers As Range
With Worksheets("ControllersInventory")
LastRowControllers = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
With Worksheets("BrakesInventory")
LastRowBrakes = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
Set Controllers = Range(Cells(1, 1), Cells(LastRowControllers, 1))
Set Brakes = Range(Cells(1, 1), Cells(LastRowBrakes, 1))
'Populate Controller_List
Worksheets("ControllerInventory").Select
With Controller_List
.RowSource "= Controllers"
End With
'Populate Brake_List
Worksheets("BrakeInventory").Select
With Brake_List
.RowSource "= Brakes"
End With
End Sub
我找到了另一种填充列表框的方法,但是我的语法错了,我想通过使用声明的范围来使用正确的编码技术。
Brake_List.RowSource = Worksheets("BrakeInventory").Range(Cells(1, 1), Cells(LastRowControllers, 1)).Address
答案 0 :(得分:0)
例如:
Dim Rws As Long, Rng As Range
Rws = Cells(Rows.Count, "A").End(xlUp).Row
Set Rng = Range(Cells(1, 1), Cells(Rws, 1))
ListBox1.List = Rng.Value
答案 1 :(得分:0)
分配.Select
它不会给你带来任何东西
.RowSource
期待一个范围。你试图给它分配一个字符串值(用“”表示),但你没有那么远,因为=
符号在引号中。
With Controller_List
.RowSource = Controllers
End With
'Populate Brake_List
With Brake_List
.RowSource = Brakes
End With
答案 2 :(得分:0)
我发现您在使用Range
或Cells
时经常忘记引用工作表。
Option Explicit
Private Sub UserForm_Initialize()
'first error when declaring variables, you declared some as variant
Dim LastRowControllers as Long, LastRowBrakes As Long 'rows can go more than 65535 (integer limit) , so i use Long
Dim Brakes as Range, Controllers As Range
With Worksheets("ControllersInventory")
LastRowControllers = .Cells(.Rows.Count, "A").End(xlUp).Row
Set Controllers = .Range(.Cells(1, 1), .Cells(LastRowControllers, 1))
End With
With Worksheets("BrakesInventory")
LastRowBrakes = .Cells(.Rows.Count, "A").End(xlUp).Row
Set Brakes = .Range(.Cells(1, 1), .Cells(LastRowBrakes, 1))
End With
'Populate Controller_List
With Controller_List
'.List= Controllers.value 'works but not dynamic
.Rowsource = Controllers.Parent.Name & "!" & Controllers.Address
End With
'Populate Brake_List
With Brake_List
'.List = Brakes.value 'works but not dynamic
.Rowsource = Brakes.Parent.Name & "!" & Brakes.Address ' example = "Sheet1!$A$1:$A$10"
End With
Set Brakes = Nothing
Set Controllers = Nothing
End Sub
另请注意,如果数据需要是动态的,我认为必须以这种方式调用userform:
Userform1.Show False