0

我正在寻找 excel 2007 的正则表达式,它可以仅在字符串末尾替换-3的所有实例,完全没有替换它(删除它)。整个字符串中有 -3 的实例,但是我只需要删除最后的那些。这已集成到宏中,因此首选使用单个正则表达式进行查找和替换。

4

3 回答 3

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 回答
1

您可以在不Regex使用 VBAInstr函数的情况下执行此操作。这是代码:

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 语句更改为 this 也可以,而且更简洁一些。

If Right (MyRange, 2) = "-3" Then MyRange=Left(MyRange, Len(MyRange)-2)
于 2013-01-02T19:06:08.600 回答
1

除非它是更大宏的一部分,否则这里不需要 VBA!只需使用这个公式,你就会得到结果:

=IF(右(A1,2)="-3",左(A1,LEN(A1)-2),A1)

(假设您的文本在单元格中A1

于 2013-02-04T07:22:53.960 回答