VBA使用变量代替属性

时间:2015-12-09 20:26:01

标签: excel-vba vba excel

我正在尝试创建一个Sub来填充一个ListBox,它基于在被调用时传递给sub的veriable。像这样的东西:

Sub RefreshItemList(sSheet As String, sItem As String, sListBox As String)
 Dim ws As Worksheet
   Set ws = ThisWorkbook.Sheets(sSheet)
 Dim x As String
   x = "a"
 Dim Row_Index As Long
   Row_Index = 1
 Dim List_Index As Integer
   List_Index = 0

   sListBox.Clear

   Do Until x = ""
      x = ws.Cells(Row_Index, 2).Value2
      If x = Item Then
         sListBox.AddItem (ws.Range("A" & Row_Index))
         sListBox.List(List_Index, 1) = ws.Range("C" & Row_Index)
         sListBox.List(List_Index, 2) = ws.Range("D" & Row_Index)
         sListBox.List(List_Index, 3) = ws.Range("E" & Row_Index)
         sListBox.List(List_Index, 4) = Round(ws.Range("N" & Row_Index), 3)

         List_Index = List_Index + 1

      End If

     Row_Index = Row_Index + 1
   Loop 

End Sub

1 个答案:

答案 0 :(得分:0)

这应该照顾它,并清理代码。在value为null字符串之前,不要使用笨拙的Do循环,只需定义一个范围对象,然后迭代范围对象的单元格。使用更加面向对象的方法也意味着我们可以摆脱不必要的变量,如xrow_indexlist_index

将这一切全部放在UserForm的模块中:

Option Explicit
Private Sub UserForm_Initialize()

    'Example of populating this during the form's initialize event
    Call RefreshItemList("Sheet3", "1", "ListBox1")

End Sub

Sub RefreshItemList(sSheet As String, sItem As String, sListBox As String)
Dim ws As Worksheet
Dim rng As Range    'Source range for the listbox control
Dim r As Range      'use thisto iterate over the "rng" Range
Dim lstBox As MSForms.ListBox

'Assign your worksheet
Set ws = ThisWorkbook.Sheets(sSheet)
'Assign your range, modify as needed
Set rng = ws.Range("A2", ws.Range("A1").End(xlDown))

'Exit sub if the first value is empty
If rng.Cells(1).Value = "" Then Exit Sub

'Get a handle on your ListBox control
Set lstBox = Me.Controls(sListBox)

With lstBox
    .Clear
    .ColumnCount = 5  'Ensure enough columns exist in the listbox
    .ColumnWidths = "20;20;20;20;20"  'Or, you can do this in the Designer. Modify as needed.
    For Each r In rng.Cells
        If r.Value2 = sItem Then
           .AddItem r(1, 1).Value                    'Column A
           .List(.ListCount - 1, 1) = r(1, 3).Value  'Column C
           .List(.ListCount - 1, 2) = r(1, 4).Value  'Column D
           .List(.ListCount - 1, 3) = r(1, 5).Value  'Column E
           '.List(.ListCount - 1, 4) = r(1, 2).Value 'Column B  -- I used this for testing only
           .List(.ListCount - 1, 4) = r(1, 12).Value 'Column N
        End If
    Next
End With

End Sub