【问题标题】:Excel VBA insert character between number and letterExcel VBA在数字和字母之间插入字符
【发布时间】:2014-08-19 10:31:06
【问题描述】:

我想要一些 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

【问题讨论】:

  • 这不是代码提供者论坛。这里的成员将帮助您修复和改进您的尝试。考虑编写代码,然后寻求帮助。
  • 按照 hawk 之前的评论,您可以遍历字符串,测试每个字符和后续字符;或者您可以使用带有替换方法的正则表达式。
  • 我会选择正则表达式。不过,您必须学会识别正确的模式。有些模式看似简单,但如果不精通RegEx,就不是在公园里散步了。

标签: string excel vba


【解决方案1】:

并且只是为了展示如何使用正则表达式来完成它,并且还允许您指定要插入的任何特定字符:

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

模式被解释为

  • \d 找到任意一个数字并将其捕获
  • (?=[A-Za-z]) 后跟一个字母

而替换是

  • $1 返回捕获组
  • &
  • 连接
  • 插入(要插入的字符串)

【讨论】:

    【解决方案2】:

    听从罗恩的建议:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多