0

我正在研究一个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
4

2 回答 2

1

试试这个使用Find方法

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
于 2013-10-20T13:20:46.990 回答
0

Your real problem is the nested loops.

If you require that both artist and title appear on the same row in "Repertoire", then you need scan down the columns only once looking for the pair.

If you require that artist appears anywhere in column F and title appears anywhere in column G, then you need first scan down column F looking for artist and then scan down column G looking for the title.

In either case, you don't need nested loops.

EDIT#1:

Based upon your comment:

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

I used Button1_Click since I was using a Forms Button for de-bug.

于 2013-10-20T13:44:09.497 回答