Excel 如何从字符串中提取特定字符?

Excel 如何从字符串中提取特定字符?,excel,vba,text-extraction,Excel,Vba,Text Extraction,我有以下字符串: 1121PDT0011 我想从字符串中提取文本字符(如PDT)并删除数字字符,请注意,PDT在字符串中的位置是可变的: 45PDT345或2PDT,我不能使用MID函数,如何在EXCEL VBA中完成我的工作?以下是我认为对于初学者来说最简单的方法: Sub Test() Dim str As String: str = "1121PDT0011" Dim x As Long For x = 0 To 9 str = Replace(str, x

我有以下字符串: 1121PDT0011 我想从字符串中提取文本字符(如PDT)并删除数字字符,请注意,PDT在字符串中的位置是可变的:
45PDT345或2PDT,我不能使用MID函数,如何在EXCEL VBA中完成我的工作?

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

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
更高级的可能是使用一些regexp对象,它实际上更像是一个文本“提取”,而不是替换我们不想要的内容:

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
试试这个UDF


然后使用replace删除数字字符。或者,如果你想要一个regexp,“我不能使用MID函数”,为什么呢?它是标准库的一部分是有原因的吗?将其与
InStr
一起使用,也可以在标准库中,也可以在
VBA.Strings
模块中使用。请更新您的问题以准确解释您正在做的事情。如果您提取“PDT”和“删除数字字符”,则输入中没有任何内容。
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