如何快速显示结果在文本框中搜索超过60000行

问题描述 投票:1回答:2

我有Excel数据库,我只想输入标签号,我会自动在文本框中显示结果......但需要30秒才能显示结果

Private Sub cmdSearch_Click()
Dim x As Long
Dim y As Long
x = Sheets("Clients").Range("A" & Rows.Count).End(xlUp).Row
For y = 1 To x
If Sheets("Clients").Cells(y, 1).Text = TextBox1.Value Then

TextBox1.Text = Sheets("Clients").Cells(y, 1)
TextBox4.Text = Sheets("Clients").Cells(y, 3)
TextBox5.Text = Sheets("Clients").Cells(y, 4)
TextBox10.Text = Sheets("Clients").Cells(y, 5)
TextBox11.Text = Sheets("Clients").Cells(y, 6)
TextBox12.Text = Sheets("Clients").Cells(y, 7)
TextBox13.Text = Sheets("Clients").Cells(y, 8)
End If
Next y
End Sub
excel vba
2个回答
2
投票

Match非常快

Private Sub cmdSearch_Click()
    Dim m As VARIANT


    With Sheets("Clients")
        m = Application.Match(TextBox1.Value, .Columns(1), 0)
        If not iserror(m) then
            TextBox4.Text = .Cells(m, 3)
            TextBox4.Text = .Cells(m, 4)
            'etc
        end if
    end with

End Sub

0
投票

循环60,000行数据将很慢。你为什么不尝试Range.Find()?文档在这里https://docs.microsoft.com/en-us/office/vba/api/excel.range.find

该页面的示例代码是

With Worksheets(1).Range("a1:a500") 
    Set c = .Find(2, lookin:=xlValues) 
    If Not c Is Nothing Then 
        firstAddress = c.Address 
        Do 
            c.Value = 5 
            Set c = .FindNext(c) 
        Loop While Not c Is Nothing
    End If 
End With

在您的代码中,您可以执行以下操作。声明一个范围变量并将其设置为find命令的结果。从找到的范围中,您可以偏移到所需的列以检索其值。

dim result as range
x = Sheets("Clients").Range("A" & Rows.Count).End(xlUp).Row
set result = Sheets("Clients").Range("A1:A" & x).Find(TextBox1.Value, lookin:=xlValues)
if not result is nothing then
   TextBox1.Text = result.value
   TextBox4.Text = result.offset(0,2).value
' and so on. use offset to get results from other columns in the row where the found range is
end if
© www.soinside.com 2019 - 2024. All rights reserved.