文字列の末尾にある-3のすべてのインスタンスのみを置き換え、まったく何も置き換えない (削除する) ことができる Excel 2007 の正規表現を探しています。文字列全体に -3 のインスタンスがありますが、最後のものだけを削除する必要があります。これはマクロに統合されているため、単一の正規表現を使用した検索と置換が推奨されます。
1801 次
3 に答える
1
Regex
VBAのInstr
機能を使用せずにこれを行うことができます。コードは次のとおりです。
Sub ReplaceIt()
Dim myRng As Range
myRange = Range("A1") ' change as needed
If InStr(Len(myRange.Text) - 2, myRange.Text, "-3") > 0 Then
myRange.Value = Left(myRange, Len(myRange) - 2)
End If
End Sub
アップデート
以下のJuriのコメントに基づいて、Ifステートメントをこれに変更することも機能し、少しクリーンになります。
If Right (MyRange, 2) = "-3" Then MyRange=Left(MyRange, Len(MyRange)-2)
于 2013-01-02T19:06:08.600 に答える
1
大きなマクロの一部でない限り、VBA は必要ありません。この式を使用するだけで、結果が得られます。
=IF(RIGHT(A1,2)="-3",LEFT(A1,LEN(A1)-2),A1)
(テキストがセルにあると仮定しますA1
)
于 2013-02-04T07:22:53.960 に答える
1
以下をお試しください:-
OPのコメントに従って編集します。
Sub mymacro()
Dim myString as String
//'--do stuff
//'-- you could just do this or save the returning
//'-- string to another string for further processing :)
MsgBox replaceAllNeg3s(myString)
End Sub
Function replaceAllNeg3s(ByRef urstring As String) As String
Dim regex As Object
Dim strtxt As String
strtxt = urstring
Set regex = CreateObject("VBScript.RegExp")
With regex
//'-- replace all -3s at the end of the String
.Pattern = "[(-3)]+$"
.Global = True
If .test(strtxt) Then
//'-- ContainsAMatch = Left(strText,Len(strText)-2)
//'-- infact you can use replace
replaceAllNeg3s = Trim(.Replace(strText,""))
Else
replaceAllNeg3s = strText
End If
End With
End Function
//'-- tested for
//'-- e.g. thistr25ing is -3-3-3-3
//'-- e.g. 25this-3stringis25someting-3-3
//'-- e.g. this-3-3-3stringis25something-5
//'-- e.g. -3this-3-3-3stringis25something-3
于 2013-01-02T18:36:01.860 に答える