我的VBA代码花很长时间才能生成一个值

时间:2018-08-20 08:56:22

标签: vba excel-vba combobox

我有一个代码可以在数据表中搜索textbox3的值,我的代码可以很好地工作,但是生成答案需要时间。这是我的代码:

Sub CODE23()
    Dim i As Long, arr

    With ThisWorkbook.Sheets("DATA")
        arr = .Range(.Range("B2"), .Cells(Rows.Count, 43) _ 
        End(xlUp).Offset(0,1)).Value
    End With

    For i = 1 To UBound(arr, 1)
        If arr(i,1)=UserForm1.TextBox3.Text Or  arr(i,1) = _
            Val(UserForm1.TextBox3.Text) Then
            UserForm1.ComboBox6.Value = "FROM " &  _ 
arr(i,43) & " TO "
        End If
    Next
End Sub

B2列具有i.d编号。第43列具有地址数据。如果用户在文本框3中输入了i.d编号,则组合框6将生成一个值,其中输入了i.d的地址。

2 个答案:

答案 0 :(得分:1)

假设您的数组设置在某处不会出错,(请确保检查UBOUND的值),我能看到加快速度的唯一方法是停止检查每个Userform1.Textbox3的值在循环中的时间。您可以执行以下操作:

valCompare = Val(UserForm1.TextBox3.Text)
txtCompare = UserForm1.TextBox3.Text

For i = 1 To UBound(arr, 1)
    If arr(i, 1) = txtCompare Or arr(i, 1) = valCompare Then
        UserForm1.ComboBox6.Value = "FROM " & arr(i, 43) & "TO "
        'Exit For
    End If
Next

另外,如果您要查找匹配项的 first 实例,则可能需要添加Exit For-但我是不知道这就是您要找的东西。

或者,您也可以将整个内容替换为Range.Find

答案 1 :(得分:0)

根据CLR答案,您可以尝试以下操作:

Sub CODE23()

    Dim arr As Range
    Dim rng As Range
    Dim valCompare as String
    Dim txtCompare as String  

    valCompare = Val(UserForm1.TextBox3.Text)
    txtCompare = UserForm1.TextBox3.Text

    Application.ScreenUpdating = False

    With ThisWorkbook.Sheets("DATA")
        Set arr = .Range("B2:" & .Cells(Rows.Count, 43).End(xlUp).Address)
    End With
    ' arr.Select ' uncomment this to check whether the correct range is taken
    For Each rng In arr
        If not isEmpty(rng) Then
            If rng.Value = txtCompare  Or rng.Value = valCompare  Then
                UserForm1.ComboBox6.Value = "FROM " & rng.Value & " TO "
                Exit For ' CAUTION - exits the for each loop after 1st hit
            End If
        End If
    Next rng

    Application.ScreenUpdating = True

End Sub