2017-12-27 1029 views
-1

我有下面的公式,我想將其轉換爲VBA中的函數。替換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 
+1

也是這個數組公式會做你想要什麼:'= LEFT(B1,MIN(FIND({ 「(」 「)」, 「 - 」 ,「/」,「,」},B1&「() - /,」)) - 1)'用Ctrl-shift-Enter確認而不是Enter。 –

回答

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 
0

您也可以在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