学习Excel技术,关注微信公众号:
excelperfect
本文继续学习wellsr.com中提供的优秀VBA程序。今天的示例也是一个自定义函数,可用来替换字符串中第N次出现子字符串。这个自定义函数结合了Mid函数、InStr函数和Replace函数来创建,非常方便使用。
下面是完整的程序代码:
Function ReplaceN(ByVal str1 As Variant, _
strFind As String, _
strReplace As String, _
N As Long, _
Optional Count As Long) As String
Dim i As Long, j As Long
Dim strM As String
strM = str1
If Count <= 0 Then Count = 1
For i = 1 To N - 1
j = InStr(1, strM, strFind)
strM = Mid(strM, j + Len(strFind),Len(strM))
Next i
If N <= 0 Then
ReplaceN = str1
Else
ReplaceN = Mid(str1, 1, Len(str1) -Len(strM)) _
& Replace(strM, strFind,strReplace, _
Start:=1, Count:=Count)
End If
End Function
示例
替换字符串中第2次出现的子字符串
Sub VBA_Replace1()
Dim str1 As String
str1 = "One fish, two fish, red fish,blue fish"
str1 = ReplaceN(str1, "fish","cat", 2)
'结果为:One fish, two cat, red fish, blue fish
Debug.Print str1
End Sub
替换从第2次出现起的2个子字符串
Sub VBA_Replace2()
Dim str1 As String
str1 = "One fish, two fish, red fish,blue fish"
str1 = ReplaceN(str1, "fish","cat", 2, 2)
'结果为:One fish, two cat, red cat, blue fish
Debug.Print str1
End Sub
程序中设置了可选的第5个参数的值,这将会告诉函数从第N次出现子字符串开始要替换的次数。
在工作表中使用
可以像内置的Excel函数一样在工作表中使用ReplaceN函数,如下图1所示。
图1