【问题标题】:Cycle through rows to match two cells on separate worksheets循环浏览行以匹配不同工作表上的两个单元格
【发布时间】:2019-10-02 13:18:52
【问题描述】:

我正在寻找循环浏览工作表 1 的列中的每一行,以匹配两个单元格(工作表 1 的 C 列中的一个单元格与工作表 2 的 E 列中的一个单元格)。

如果有匹配,我想对相邻的单元格执行一个操作(我稍后会解决这个问题),然后继续循环,直到没有更多匹配为止。

到目前为止,我有以下内容:

Sub Test3()
    Dim x As String
    Dim found As Boolean
    ' Select first line of data.
    Worksheets("PLANNER_ONGOING_DISPLAY_SHEET").Activate
    Range("C4").Select
    ' Set search variable value.
    x = "test 73"
    ' Set Boolean variable "found" to false.
    found = False
    ' Set Do loop to stop at empty cell.
    Do Until IsEmpty(ActiveCell)
        ' Check active cell for search value.
        If ActiveCell.Value = x Then
            found = True
            Exit Do
        End If
        ' Step down 1 row from present location.
        ActiveCell.Offset(1, 0).Select
    Loop
    ' Check for found.
    If found = True Then
        MsgBox "Value found in cell " & ActiveCell.Address
    Else
        MsgBox "Value not found"
    End If
End Sub

【问题讨论】:

    标签: excel vba loops match


    【解决方案1】:

    您可以采取更简单的方法,同时avoiding .Activate and .Select

    Sub Test3()
      Dim x As String, y As String
      Dim found As Boolean
      Dim i As Integer, lastRow As Long
    
      lastRow = Worksheets("PLANNER_ONGOING_DISPLAY_SHEET").Cells(Rows.Count, 3).End(xlUp).Row
    
      x = "test 73"
    
      For i = 4 To lastRow
        'If you need to compare it to a cell in sheet2 you can also set the value of x here
        y = Worksheets("PLANNER_ONGOING_DISPLAY_SHEET").Cells(i, 3).Value2
        If y = x Then
            ' Do action here, example:
            MsgBox "Value found in cell " & "C" & i
        End If
    
      Next i
    
    End Sub
    

    这将遍历C 列中所有使用的单元格,并将它们与 x 进行比较。如果单元格匹配,则通过MsgBox 返回其行号。

    【讨论】:

    • lastRow = Worksheets("PLANNER_ONGOING_DISPLAY_SHEET").cells(rows.count,3).End(xlUp).Row
    • @HarassedDad 你说得对,我也注意到了。现已更正。
    • 非常感谢!跟进 - 如果我想匹配另一个单元格而不是文本“test 73”,有没有简单的方法可以做到这一点?例如,“表 2”上的单元格 E2?
    • 将此x = "test 73" 替换为x = Sheets("Sheet2").Cells(2, 5).Value。如果这解决了您的问题,请考虑投票并接受答案,以便其他人更容易找到它。
    猜你喜欢
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    • 2016-06-16
    相关资源
    最近更新 更多