查找具有特定长度VBA的字符串

时间:2016-09-26 13:24:24

标签: excel vba excel-vba

我正在尝试使用VBA查找一个字符串,其中包含4个字符,列中没有空格。单元格中有更多字符串。我想避免使用公式。

2 个答案:

答案 0 :(得分:2)

假设列" A"是一个

Option Explicit

Sub main()
    Dim cell As Range
    Dim arr As Variant, arrElem As Variant

    With Worksheets("Strings") '<--| change "Strings" to your actual worksheet name
        For Each cell In .Range("A1", .Cells(.Rows.Count, "A").End(xlUp))
            arr = Split(Replace(cell.Value, "  ", " "), " ") '<--| change "A"'s to your actual relevant column index
            For Each arrElem In arr
                If Len(arrElem) = 4 Then MsgBox arrElem
            Next arrElem
        Next cell
    End With
End Sub

答案 1 :(得分:0)

我读了你的问题,因为你有一个特定的字符串,四个字符长,你需要在单元格中找到。这个会做到这一点。只需将"test"替换为您的字符串,并在必要时更改列:

Sub findCells()
Dim rCells() As Variant
Dim str As String
Dim col As Integer

str = "test" ' replace this with the text you want to find
col = 1 ' to search Column A

Dim i As Long

For i = 1 To Cells(Rows.Count, col).End(xlUp).Row
    If InStr(1, Cells(i, col), str) Then
        ' Match found, add code here to do
        ' whatever you need.
        Debug.Print "Match found in cell: " & Cells(i, col).Address
    End If
Next i

End Sub