MsgBox值以4以上找到的值开头。

时间:2018-01-31 14:04:11

标签: excel vba excel-vba

所以我正在运行一个宏来查找原始数据中的客户。表1是客户列表,表2是大量原始数据。在循环中有一个MsgBox,显示数据中是否有客户。数据看起来像这样:

如何让MsgBox显示以4开头的第一个值。

以下是我正在使用的代码。

Public Sub TestMe()

Dim r1      As Variant
Dim r2      As Variant
Dim r3      As Variant

Dim rData   As Variant
Dim r       As Variant
Dim result  As Variant

rData = Application.Transpose(Worksheets(2).Range("A:A"))

r1 = Application.Transpose(Worksheets(1).Range("C2:C33"))
r2 = Application.Transpose(Worksheets(1).Range("C34:C35"))
r3 = Application.Transpose(Worksheets(1).Range("C36:C43"))


For Each r In r1
    result = Application.Match(r, rData, 0)
    If Not IsError(result) Then
        MsgBox r
    End If
Next r

For Each r In r2
    result = Application.Match(r, rData, 0)
    If Not IsError(result) Then
        MsgBox r
    End If
Next r

For Each r In r3
    result = Application.Match(r, rData, 0)
    If Not IsError(result) Then
        MsgBox r
    End If
Next r


MsgBox "search ended."

End Sub

2 个答案:

答案 0 :(得分:1)

试试这样:

Public Sub TestMe()

    Dim bigRange    As Range
    Dim myCell      As Range

    Set bigRange = Worksheets(2).Range("A1:A9")
    For Each myCell In bigRange
        If Left(myCell, 1) = 4 Then
            MsgBox myCell
            Exit For
        End If
    Next myCell

End Sub

它将循环遍历bigRange中的单元格,并检查单元格的第一个字符是否为4。如果是4,则会显示MsgBox并退出循环。

答案 1 :(得分:1)

我认为你想要这些方面的东西。在较高级别,代码循环第一个工作表的第一列中的单元格,以提取客户ID。在第二张表中搜索每个id。如果找到了,我们会向上工作(使用offset property)寻找一个从4开始的单元格。

Sub findCustomer()
    Dim customerWs As Worksheet         ' Ref to the customer worksheet.
    Dim rawWs As Worksheet              ' Ref to the raw worksheet.
    Dim currentCustomer As Range        ' Used to loop over all customers.
    Dim findCustomer As Range           ' Used to search raw for current customer.
    Dim offsetRow As Integer            ' Used to search above found customer for value starting 4.

    Set customerWs = ThisWorkbook.Sheets("Sheet1")
    Set rawWs = ThisWorkbook.Sheets("Sheet2")

    ' Assumes all customer ids are located in the first column
    ' of sheet 1.
    ' Loop executed once for each cell in that column.
    For Each currentCustomer In customerWs.UsedRange.Columns(1).Cells

        ' Look for the current customer.
        Set findCustomer = rawWs.Columns(1).Find(currentCustomer.Value)
        If Not findCustomer Is Nothing Then

            ' Found one.
            ' Work up one row at a time looking for 4.
            For offsetRow = 1 To (findCustomer.Row - 1)

                If findCustomer.Offset(offsetRow * -1, 0).Value Like "4*" Then

                    ' Match found.
                    ' Inform user and exit.
                    MsgBox "Customer: " & findCustomer.Value & ". 4 Found: " & findCustomer.Offset(offsetRow * -1, 0).Address & "."
                    Exit For
                End If
            Next
        End If
    Next
End Sub