我正在使用CommandButton
宏搜索另一个工作表中的列以查找文本字符串,如果找到,则将“找到”文本添加到原始工作表中的列。搜索文本字符串由原始工作表中两个特定单元格中的文本定义。
我构建了一些工作代码,用于查找另一个工作表中某个范围内的文本,但是在处理1000行时速度非常慢。在这种情况下,我如何将我的代码转换为使用循环(我认为这是最快的方法)?
我目前的代码:
Private Sub CommandButton1_Click()
On Error Resume Next
Application.ScreenUpdating = False
Dim artist As String
artist = ActiveSheet.Range("C4").Text
Dim title As String
title = ActiveSheet.Range("C5").Text
Dim tick As String
tick = "found"
Dim c As Range
Dim d As Range
For Each c In Sheets("Repertoire").Range("F1:F2000")
For Each d In Sheets("Repertoire").Range("G1:G2000")
If c.Value = artist And d.Value = title Then
Sheets("Dashboard").Range("F4").Value = artist
Sheets("Dashboard").Range("G4").Value = title
Sheets("Dashboard").Range("H4").Value = tick
End If
Next
Next
End Sub
答案 0 :(得分:1)
Private Sub CommandButton1_Click()
Dim artistFound As Range, titleFound As Range, artist As String, title As String, c As Range, d As Range
artist = ActiveSheet.Range("C4")
title = ActiveSheet.Range("C5")
Set c = Sheets("Repertoire").Range("F1:F2000")
Set d = Sheets("Repertoire").Range("G1:G2000")
Set artistFound = c.Find(What:=artist, After:=c.Cells(1, 1), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
Set titleFound = d.Find(What:=title, After:=d.Cells(1, 1), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If Not artistFound Is Nothing And Not titleFound Is Nothing Then
With Sheets("Dashboard")
.Range("F4").Value = artist
.Range("G4").Value = title
.Range("H4").Value = "found"
End With
End If
End Sub
答案 1 :(得分:0)
你真正的问题是嵌套循环。
如果您要求艺术家和标题同时显示在“保留曲目”中的同一行,则只需在查找该对时扫描列。
如果您要求该艺术家出现在F列的任何位置,并且标题出现在G列的任何位置,则您需要首先向下扫描F列寻找艺术家,然后向下扫描G列以寻找标题。
在任何一种情况下,您都不需要嵌套循环。
修改#1 强>:
根据您的评论:
Sub Button1_Click()
artist = ActiveSheet.Range("C4")
title = ActiveSheet.Range("C5")
tick = "Found"
Set c = Sheets("Repertoire").Range("F1:F2000")
Set d = Sheets("Repertoire").Range("G1:G2000")
For Each cc In c
If cc.Value = artist And cc.Offset(0, 1).Value = title Then
Sheets("Dashboard").Range("F4").Value = artist
Sheets("Dashboard").Range("G4").Value = title
Sheets("Dashboard").Range("H4").Value = tick
Exit Sub
End If
Next cc
End Sub
我使用 Button1_Click ,因为我使用表单按钮进行删除。