查找具有特定长度VBA的字符串
我正在尝试使用VBA查找一个列中只有4个字符且没有空格的字符串。单元格中有更多字符串。我希望避免使用公式 假设列“A”是查找具有特定长度VBA的字符串,vba,excel,Vba,Excel,我正在尝试使用VBA查找一个列中只有4个字符且没有空格的字符串。单元格中有更多字符串。我希望避免使用公式 假设列“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
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
选项显式
副标题()
暗淡单元格作为范围
Dim arr作为变型,arrElem作为变型
对于工作表(“字符串”)”我阅读了您的问题,因为您有一个特定的字符串,四个字符长,需要在单元格中查找。这个就可以了。只需将“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
VBA有一个名为Len
的函数,它将返回给定值的长度。您可以在单元格、单元格值的一部分或以任何其他方式使用它。如果您能给出一个输入示例,并说明您希望如何格式化输出,这将有所帮助。另外,请显示您为尝试执行此操作而编写的代码?我想在列上执行此操作,该列基本上是由MODI office module创建的OCR文本识别方法的结果。一列中大约有90行,每个单元格中有几个字符串。我想在此特定列中提取字符串4个字母/数字。@eurano请将答案标记为正确,以帮助其他人寻找同一问题的答案。eurano,不客气。还有。。。。是的,正如@SkipIntro指出的,请将答案标记为已接受。非常感谢。