【问题标题】:How I can extract specific characters form a string?如何从字符串中提取特定字符?
【发布时间】:2021-04-15 16:28:13
【问题描述】:

我有以下字符串: 1121PDT0011 我想从 STRING 中提取像 PDT 这样的文本字符并删除数字字符,请注意 PDT 在 STRING 中的位置是可变的: 45PDT345 或 2PDT 无法使用 MID 功能,如何在 EXCEL VBA 中工作?

【问题讨论】:

  • 然后使用替换删除数字字符。或者如果你想要一个正则表达式。
  • “我不能使用 MID 功能” - 为什么?它是标准库的一部分是有原因的吗?与InStr 一起使用,同样在标准库中,也在VBA.Strings 模块中。
  • 请更新您的问题以准确解释您在做什么。如果您提取“PDT”和“删除数字字符”,那么您的输入中将没有任何内容。

标签: excel vba text-extraction


【解决方案1】:

以下是我认为对于初学者来说最简单的方法:

Sub Test()

Dim str As String: str = "1121PDT0011"
Dim x As Long

For x = 0 To 9
    str = Replace(str, x, "")
Next

Debug.Print str

End Sub

更高级的可能是使用一些正则表达式对象,它实际上更像是文本“提取”,而不是替换我们不想要的:

Sub Test()

Dim str As String: str = "1121PDT0011"

With CreateObject("vbscript.regexp")
    .Pattern = "[A-Z]+"
    If .Test(str) Then
        str = .Execute(str)(0)
    End If
End With

Debug.Print str

End Sub

【讨论】:

    【解决方案2】:

    试试这个 UDF。

    Function TextOnly(pWorkRng As Range) As String
        Dim xValue      As String
        Dim OutValue    As String
        xValue = pWorkRng.Value
        For xIndex = 1 To VBA.Len(xValue)
            If Not VBA.IsNumeric(VBA.Mid(xValue, xIndex, 1)) Then
                OutValue = OutValue & VBA.Mid(xValue, xIndex, 1)
            End If
        Next
        TextOnly = OutValue
    End Function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2017-07-28
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多