我需要找到一个长度可变的字符串模式,并在该字符串模式后添加一个逗号和空格。例如,搜索字符串“ Cat。123”,我想将该字符串替换为值“ Cat。123,”(即,在“ Cat。123”的末尾添加一个逗号,然后添加一个空格)。我正在使用Mac Office 2011,因此任何代码都必须与Mac版本的Excel配合使用。
我尝试使用Replace.Regex,Split和我可以找到的所有其他Replace函数。下面的代码是我为此想出的最好的代码,但是没有在字符串模式的末尾添加逗号和空格。
Sub test()
Dim r As Range, x, y
Set r = Cells.Find("?*, Cat. *", , , 1)
If Not r Is Nothing Then
Do
' Search for any string with the pattern Cat. 123, Cat. 14, etc
x = Split(r.Value, " Cat. ")
If x(UBound(x)) Like "* *" Then
' Replace string Cat. 123 with the new string Cat. 123,
y = Split(x(UBound(x)))
x(0) = "Cat. " & y(0) & ", " & x(0)
x(UBound(x)) = y(1)
Else
y = x(UBound(x))
x(0) = "Cat. " & y & ", " & x(0)
x(UBound(x)) = ""
End If
r.Value = Join(x)
Set r = Cells.FindNext(r)
Loop Until r Is Nothing
End If
End Sub
因此,每个单元格的输出都包含类似于以下示例的模式:“ Cat。123”“ Cat。1”“ Cat。34”“ Cat。4567”,将更改为“ Cat。123,”“目录1,“”目录34“,”目录4567“,”注意:原始字符串在“目录”一词之后总是有一个句点,然后是一个空格,然后是一个数字。最多显示四位数,如上所示。
答案 0 :(得分:1)
尝试一下(这次没有vbscript依赖的正则表达式):
Sub tgr()
Dim aData As Variant
Dim sTemp As String
Dim lCatLoc As Long
Dim lNextSpace As Long
Dim i As Long, j As Long
With ActiveSheet.UsedRange
If .Cells.Count = 1 Then
ReDim aData(1 To 1, 1 To 1)
aData(1, 1) = .Value
Else
aData = .Value
End If
For i = 1 To UBound(aData, 1)
For j = 1 To UBound(aData, 2)
If Len(aData(i, j)) > 0 Then
If aData(i, j) Like "*Cat. [0-9]*" Then
lCatLoc = InStr(1, aData(i, j), "Cat. ", vbTextCompare)
lNextSpace = InStr(lCatLoc + 5, aData(i, j) & " ", " ", vbTextCompare)
sTemp = Mid(aData(i, j), lCatLoc, lNextSpace - lCatLoc)
If Right(sTemp, 1) <> "," Then aData(i, j) = Replace(aData(i, j), sTemp, sTemp & ", ")
End If
End If
Next j
Next i
.Value = aData
End With
End Sub