我想要一些VBA代码,它允许我检测字符串是否包含数字后跟字母的任何实例,然后在它们之间插入新字符。例如:
用户输入以下字符串:
4x^2+3x
函数返回:
4*x^2+3*x
提前致谢。
编辑:感谢您的建议,我认为我有它的工作,但我想看看你是否可以改进我所拥有的:
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
答案 0 :(得分:3)
只是为了说明如何使用正则表达式完成它,并且还允许您指定要插入的任何特定字符:
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
模式被解释为
替换是
答案 1 :(得分:0)
遵循罗恩的建议:
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