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

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

我想要一些 VBA 代码,可以让我检测字符串中是否包含数字后跟字母的任何实例,然后在它们之间插入一个新字符。例如:

用户输入以下字符串:

4x^2+3x

函数返回:

4*x^2+3*x

提前致谢。

答案1

这将做到这一点:

Sub Button2_Click()
    Range("D5").Value = FixString(Range("B4").Text, "*")
End Sub

Function FixString(sIn As String, sAdd As String) As String
    Dim sOut As String, sChNow As String, _
      nChNow As Integer, nChNext As String, _
      nLen As Integer
    nLen = Len(sIn)
    If nLen > 1 Then
        For i = 1 To nLen - 1
            sChNow = Mid(sIn, i, 1)
            sOut = sOut & sChNow
            nChNow = Asc(sChNow)
            nChNext = Asc(Mid(sIn, i + 1, 1))
            If ((nChNext >= 65 And nChNext <= 90) Or _
               (nChNext >= 97 And nChNext <= 122)) And _
               ((nChNow >= 48 And nChNow <= 57)) Then
                sOut = sOut & sAdd
            End If
        Next i
        FixString = sOut & Right(sIn, 1)
    Else
        FixString = sIn
    End If
End Function

只需编辑 Button2_Click() 子程序来适应您的情况。

相关内容