我试图自动更新组合框列表。仅当我关闭然后打开工作簿时,或者当我按下VBA上的停止按钮并再次运行宏时,它才会正确更新。我有以下VBA代码。
Private Sub UserForm_Initialize()
Dim cod As Range
Dim pro As Range
Dim cli As Range
Dim ws As Worksheet
Dim ws5 As Worksheet
Set ws = Worksheets("ListaProductos")
Set ws5 = Worksheets("ListaClientes")
For Each cod In ws.Range("CodigoProductoLista")
With Me.codigo
.AddItem cod.Value
.List(.ListCount - 1, 1) = cod.Offset(0, 1).Value
End With
Next cod
For Each cli In ws5.Range("ClienteLista")
With Me.cliente
.AddItem cli.Value
.List(.ListCount - 1, 1) = cli.Offset(0, 1).Value
End With
Next cli
No.Value = True
calendario2.Visible = False
calendario2.Refresh
calendario = Date
Me.codigo.SetFocus
End Sub
谢谢!
答案 0 :(得分:1)
您可以再次调用UserForm_Initialize
程序,但必须先清除列表。您可以在命令按钮或事件中使用它。
答案 1 :(得分:0)
只有在加载表单时才会触发Initialize事件。在表单中添加一个名为cmdRepopulate的按钮,然后使用此代码:
Option Explicit
Private Sub UserForm_Initialize()
PopulateCodigoProductoLista
PopulateClienteLista
FinishingOff
End Sub
Private Sub PopulateCodigoProductoLista()
Dim rngData As Range
With Worksheets("ListaProductos").Range("CodigoProductoLista")
Set rngData = .Resize(.Rows.Count, 2)
End With
PopulateComboUsingRange Me.codigo, rngData
End Sub
Private Sub PopulateClienteLista()
Dim rngData As Range
With Worksheets("ListaClientes").Range("ClienteLista")
Set rngData = .Resize(.Rows.Count, 2)
End With
PopulateComboUsingRange Me.cliente, rngData
End Sub
Private Sub FinishingOff()
No.Value = True
calendario2.Visible = False
calendario2.Refresh
calendario = Date
Me.codigo.SetFocus
End Sub
Private Sub PopulateComboUsingRange(cboDataDestination As MSForms.ComboBox, _
rngDataSource As Range)
Dim lngCounter As Long
With cboDataDestination
.Clear
For lngCounter = 1 To rngDataSource.Rows.Count
.AddItem rngDataSource.Cells(lngCounter, 1)
If rngDataSource.Columns.Count = 2 Then
.List(.ListCount - 1, 1) = rngDataSource.Cells(lngCounter, 2)
End If
Next
End With
End Sub
Private Sub cmdRepopulate_Click()
PopulateCodigoProductoLista
PopulateClienteLista
FinishingOff
End Sub
有一些限制(因为为时已晚),特别是通用的组合人口常规,但目前它应该对你有好处。代码将在窗体的Initialize事件上运行,并且每当您单击repopulate按钮时。我决定使用你的命名范围 - 没有变化。
请注意使用通用proc来填充组合。如果你在同一个工作簿中的其他表单上有其他组合,你可以将该proc移动到一个单独的模块,将其更改为Public(而不是Private),并通过重用代码来节省大量的输入。