Excel VBA在数字和字母之间插入字符

我想要一些VBA代码,这将允许我检测一个string是否包含任何数字后跟一个字母的实例,然后在它们之间插入一个新的字符。 例如:

用户input以下string:

4x^2+3x 

函数返回:

 4*x^2+3*x 

提前致谢。

编辑:感谢您的build议家伙,我想我有它的工作,但我想看看如果你能改善我有:

 Sub insertStr() On Error Resume Next Dim originalString As String Dim newLeft As String Dim newRight As String originalString = Cells(1, 1).Value Repeat: For i = 1 To Len(originalString) If IsNumeric(Mid(originalString, i, 1)) = True Then Select Case Asc(Mid(originalString, i + 1, 1)) Case 65 To 90, 97 To 122 newLeft = Left(originalString, i) newRight = Right(originalString, Len(originalString) - i) originalString = newLeft & "*" & newRight GoTo Repeat Case Else GoTo Nexti End Select End If Nexti: Next i End Sub 

遵循罗恩的build议:

 Public Function InsertStar(sIn As String) As String Dim L As Long, temp As String, CH As String L = Len(sIn) temp = Left(sIn, 1) For i = 2 To L CH = Mid(sIn, i, 1) If IsLetter(CH) And IsNumeric(Right(temp, 1)) Then temp = temp & "*" End If temp = temp & CH Next i InsertStar = temp End Function Public Function IsLetter(sIn As String) As Boolean If sIn Like "[a-zA-Z]" Then IsLetter = True Else IsLetter = False End If End Function 

只是为了展示如何使用正则expression式来完成,还允许你指定任何特定的字符来插入:

 Option Explicit Function InsertChar(S As String, Insert As String) As String Dim RE As Object Set RE = CreateObject("vbscript.regexp") With RE .Global = True .Pattern = "(\d)(?=[A-Za-z])" InsertChar = .Replace(S, "$1" & Insert) End With End Function 

该模式被解释为

  • \ dfind任何号码并捕获它
  • (?= [A-Za-z])后跟一个字母

而更换是

  • $ 1返回捕获组
  • 连接在一起
  • 插入 (要插入的string)