从文本框/列表框创建数组

时间:2017-06-09 11:58:02

标签: arrays excel vba excel-vba listbox

我将自己归类为编程初学者。我有一个userform,它首先查找用户提供的数字。实施例12345,12346,12347。搜索输入到文本框中的数字,然后将其作为有效数字添加到列表框中。用户输入所需的所有号码后,他们应该能够点击更改并相应地更新记录。

Private Sub Change_Click()
Dim i As Long

For i = LBound(RunArray) To UBound(RunArray)
    ' Code to update each record, still working on it.
Next

End Sub

Private Sub RunNumber_KeyDown(ByVal KeyCode As MSForms.ReturnInteger,     ByVal Shift As Integer)
Dim RunArray() As String
Dim RunCount As Integer
RunCount = 0

If KeyCode = 13 Then
    With Sheets("Sheet1").Range("A:A")
        Set RunFind = .Find(What:=RunNumber, _
                     After:=.Cells(.Cells.count), _
                     LookIn:=xlValues, _
                     LookAt:=xlWhole, _
                     SearchOrder:=xlByRows, _
                     SearchDirection:=xlNext, _
                     MatchCase:=False)
        If Not RunFind Is Nothing Then
            ReDim Preserve RunArray(RunCount)
            RunArray(RunCount) = RunNumber.Value
            RunNumberList.AddItem RunNumber.Value
            RunNumber.Value = ""
            RunCount = RunCount + 1
        Else
            MsgBox "The Run Number you entered was not found, Please the number and try again."
            RunNumber.Value = ""
        End If
    End With
End If

End Sub

2 个答案:

答案 0 :(得分:0)

Private Sub CreateArrayFromListbox()
  Dim nIndex As Integer
  Dim vArray() As Variant
  ReDim vArray(ListBox1.ListCount - 1)

  For nIndex = 0 To ListBox1.ListCount - 1
    vArray(nIndex) = ListBox1.List(nIndex)
  Next
End Sub

答案 1 :(得分:0)

我有一个例子,如何使用组合框,(它与列表框相同,只需相应地更改名称。

Option Explicit

Private Sub UserForm_Initialize()
Dim i&
Dim Arr()
With Me.ComboBox1
    For i = 1 To 1000
        .AddItem "Item " & i
    Next i

    Arr = .List

    .Clear
End With

For i = 0 To 999
    Debug.Print Arr(i, 0)
Next i

Erase Arr
End Sub

这只是一个示例代码,在实际编码中,你不会在早期清除组合框,或者擦除数组。

结果显示在即时窗口中(alt-F11和Ctrl-g)。

注意:数组是2维的,基于0 {({1}},在Option base 1之后可以使整个模块从1开始(数组从1开始)。