在VBA中替换多个字符实例

问题描述 投票:-1回答:2

我有以下公式,我想转换为VBA中的函数。

=IFERROR(LEFT(B1,(FIND(",",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(B1,"(",","),"-",","),"/",","))-1)),SUBSTITUTE(B1,".", ""))

我尝试了一些东西,但是无法让它正常工作。 Test

Function CharacterSwap(text)

Dim Old As Variant
Dim Comma As Variant

Old = Array(")", "(", "-", "/")
Comma = Array(",", ",", ",", ",")

For i = LBound(Old) To UBound(Comma)


    If InStr(1, text, Old(i), vbBinaryCompare) > 0 Then

        CharacterSwap = Replace(text, Old(i), Comma(i), 1, 1, vbBinaryCompare)

    End If


Next i

End Function

Function SCRUB(text)

If InStr(1, CharacterSwap(text), ",", vbBinaryCompare) > 0 Then


SCRUB = Left((CharacterSwap(text)), InStr(1, (CharacterSwap(text)), ",") - 1)

Else

SCRUB = text

End If
End Function
excel vba function replace excel-formula
2个回答
1
投票

您也可以使用正则表达式在VBA中完成此操作。如果我理解正确,你想用逗号替换字符串中()/-集合中的任何/所有字符。

Option Explicit
Function CharacterSwap(S As String) As String
    Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
With RE
    .Pattern = "[()/-]"
    .Global = True
    CharacterSwap = .Replace(S, ",")
End With

End Function

如果你碰巧在上面的.Pattern中为字符类添加了字符,你应该知道破折号-必须是类中列出的第一个或最后一个字符。

如果它在其他任何地方,它将被解释为指示由前后字符限定的字符范围。

换一种说法

  • [0-9]将包括所有数字。
  • [-09]只包括dash09

0
投票
Function CharacterSwap(text)

Dim Old As Variant
Dim Comma As Variant

Old = Array(")", "(", "-", "/")
Comma = Array(",", ",", ",", ",")

For i = LBound(Old) To UBound(Old)
    If InStr(1, text, Old(i), vbBinaryCompare) > 0 Then
        'adjust the text in the text variable to maintain the changes
        text = Replace(text, Old(i), Comma(i), 1, 1, vbBinaryCompare)
    End If
Next i

CharacterSwap = text

End Function

Function SCRUB(text)
Dim newtext As String
'put output into a variable to avoid the multiple calls
newtext = CharacterSwap(text)

If InStr(1, newtext, ",", vbBinaryCompare) > 0 Then
    SCRUB = Left(newtext, InStr(1, newtext, ",") - 1)
Else

SCRUB = text

End If
End Function

但是这个简单的函数可以用更少的行来完成所有这些:

Function Scrub(text)
With Application
    Scrub = Left(text, .Min(.Find(Array("(", ")", "-", "/", ","), text & "()-/,")) - 1)
End With
End Function
© www.soinside.com 2019 - 2024. All rights reserved.