查找以特定数字开头的每个单元格的单元格地址

时间:2018-05-20 05:18:22

标签: vba excel-vba excel

我正在寻找一个代码,可以找到以数字" 2347"开头的每个单元格。在列L中,我希望得到这些单元格的单元格地址并将其显示在MessageBox中,例如" Msgbox:Cells L3500:L3722的值从" 2347"开始。 "

Sub Findrow()

Dim MyVal As Integer
Dim LastRow As Long


MyVal = LEFT(c.Value,4) = "2347" _
LastRow = Cells(Rows.Count, "L").End(xlUp).Row 

For Each c In Range("L2:L" & LastRow) 

If c.Value = Myval Then

到目前为止,这是我的代码。希望有人可以帮助我!

2 个答案:

答案 0 :(得分:2)

使用数组非常快

Option Explicit

Public Sub FindIDInColL()

    Const VID = "2347"   'Value to find

    Dim ws As Worksheet, arrCol As Variant, found As Variant

    Set ws = ActiveSheet 'Or Set ws = ThisWorkbook.Worksheets("Sheet3")
    arrCol = ws.Range(ws.Cells(2, "L"), ws.Cells(ws.Rows.Count, "L").End(xlUp))
    ReDim found(1 To UBound(arrCol))

    Dim r As Long, f As Long, msg As String

    f = 1
    For r = 1 To UBound(arrCol)             'Iterate vals in col L, excluding header row
        If Not IsError(arrCol(r, 1)) Then   'Ignore errors
            If Len(arrCol(r, 1)) > 3 Then   'Check only strings longer than 3 letters
                If Left$(arrCol(r, 1), 4) = VID Then    'Check first 4 letters
                    found(f) = r + 1        'Capture rows containing value (header offset)
                    f = f + 1
                End If
            End If
        End If
    Next

    If f > 1 Then                           'If any cells found
        ReDim Preserve found(1 To f - 1)    'Drop unused array items
        msg = "Cells in col L starting with """ & VID & """" & vbNewLine & vbNewLine
        MsgBox msg & " - L" & Join(found, ", L"), , "Total Found: " & f - 1
    Else
        MsgBox "No cells starting with """ & VID & """ found in col L", , "No matches"
    End If
End Sub

使用这些功能的string versions时速度更快

  • Left$() Mid$() Right$() Chr$() ChrW$() UCase$() LCase$()

  • LTrim$() RTrim$() Trim$() Space$() String$() Format$()

  • Hex$() Oct$() Str$() Error$

QHarr

指出,它们效率更高(Null不是问题)

答案 1 :(得分:1)

你可以试试这个:

Option Explicit

Sub Findrow()
    Dim MyVal As String ' "2347" is a String
    Dim LastRow As Long
    Dim c As Range, myCells As Range

    MyVal = "2347"
    LastRow = cells(Rows.Count, "L").End(xlUp).row

    Set myCells = Range("M2") 'initialize cells with a dummy cell certainly out of relevant one
    For Each c In Range("L2:L" & LastRow)
        If Left(c.Value2, 4) = MyVal Then Set myCells = Union(myCells, c) ' if current cell matches criteria then add it to cells
    Next
    If myCells.Count > 1 Then MsgBox "Cells " & Intersect(myCells, Range("L:L")).Address(False, False) & " have values starting with ‘2347’" ' if there are other cells than the dummy one then get rid of this latter and show their addresses
End Sub