我的代码完美地将过滤后的数据返回到表单上的三列TextBoxes。当我在调试中逐步执行它时,我可以看到执行我的新手(但工作)代码需要很长时间。我已经录制了宏来试图理解我如何使用AutoFilter脚本来做同样的事情&所以有一个更快的剧本,但我害怕我被打败。任何人都可以告诉我如何做到这一点,或者我是否应该这么做呢?
Private Sub CommandButton1_Click()
Dim i As Integer, c As Integer, d As Integer
Dim e As Integer, f As Integer, g As Integer
Dim lstrw As Integer, ws As Worksheet
Dim MySerNum As String, MyLocation As String
Dim MySearchValue As String, MyStatus As String
MySearchValue = "x" 'search column for cells that contain only the letter "x"
Set ws = Sheets(2)
'The user will type an "x" in column N at the rows...
'he wishes to return data from to the form TextBoxes
lstrw = ws.Range("N" & Rows.Count).End(xlUp).Row
'find how many cells contain string "x"
For f = 1 To lstrw
If ws.Cells(f, 14).Value = MySearchValue Then
e = e + 1
End If
Next f
' loop to find occurrence of "x" and load variables
For i = 1 To lstrw
'the adjacent textbox on the form to TextBox1...
'is TextBox16 hence the +15 below
If ws.Cells(i, 14).Value = MySearchValue Then
MySerNum = ws.Cells(i, 2).Value
End If
If ws.Cells(i, 14).Value = MySearchValue Then
MyLocation = ws.Cells(i, 4).Value
End If
If ws.Cells(i, 14).Value = MySearchValue Then
MyStatus = ws.Cells(i, 5).Value
End If
d = c + 15
g = d + 15
Me.Controls("TextBox" & c).Value = MySerNum
Me.Controls("TextBox" & d).Value = MyLocation
Me.Controls("TextBox" & g).Value = MyStatus
If ws.Cells(i, 14).Value = MySearchValue Then
c = c + 1
End If
Next i
End Sub
答案 0 :(得分:1)
那就是说 - 这里有几个提示:
变化:
For i = 1 To lstrw
'the adjacent textbox on the form to TextBox1...
'is TextBox16 hence the +15 below
If ws.Cells(i, 14).Value = MySearchValue Then
MySerNum = ws.Cells(i, 2).Value
End If
If ws.Cells(i, 14).Value = MySearchValue Then
MyLocation = ws.Cells(i, 4).Value
End If
If ws.Cells(i, 14).Value = MySearchValue Then
MyStatus = ws.Cells(i, 5).Value
End If
d = c + 15
g = d + 15
Me.Controls("TextBox" & c).Value = MySerNum
Me.Controls("TextBox" & d).Value = MyLocation
Me.Controls("TextBox" & g).Value = MyStatus
If ws.Cells(i, 14).Value = MySearchValue Then
c = c + 1
End If
Next i
要:
For i = 1 To lstrw
'the adjacent textbox on the form to TextBox1...
'is TextBox16 hence the +15 below
If ws.Cells(i, 14).Value = MySearchValue Then
Me.Controls("TextBox" & c).Value = ws.Cells(i, 2).Value
d = c + 15
Me.Controls("TextBox" & d).Value = ws.Cells(i, 4).Value
g = d + 15
Me.Controls("TextBox" & g).Value = ws.Cells(i, 5).Value
c = c + 1
End If
Next i
这样做会删除所有中间My...
变量,因此您可以删除它们的Dim
语句。如果以后需要它们,可以在循环结束时设置它们一次。这会加快速度。