将文本提取到表而不使用特殊字符

时间:2014-07-02 11:01:29

标签: vba

这个脚本将从整个字符串中提取()之间的每个文本。现在我准备它作为一个函数,因为许多字符串将采取在那之下,然后我想在表/或列表中添加每个提取的单词。 ()之间的每个提取文本应该没有特殊字符,有时可能会出现在文本中,我想剪切它们的字符串(我只想留下AZ az 0-9我怎么能这样做?

Sub Main()    
    Dim s$
    s = "hsus(irt)bla dsd (got)(rifk)"    
    Debug.Print extract_value(s)    
End Sub

Public Function extract_value$(s$)    
    Dim returnS$
    Dim v
    v = Split(s, Chr(40))

    For Each Item In v
        If InStr(Item, Chr(41)) Then
            returnS = returnS & Chr(32) & Split(Item, ")")(0)
        End If
    Next

    extract_value = Trim$(returnS)
End Function

2 个答案:

答案 0 :(得分:1)

解析时,您可以使用辅助函数使用ASCII编码检查字母和数字。

Function validChr(chr As String) as Boolean
Dim ascCode As Integer

ascCode = Asc(chr)

If ascCode >= 65 And ascCode <= 90 Then 'Uppercase
    validChr = True
ElseIf ascCode >= 97 And ascCode <= 122 Then 'Lowercase
    validChr = True
ElseIf ascCode >= 48 And ascCode <= 57 Then 'Numbers
    validChr = True
Else
    validChr = False

End Function

您还可以查看使用RegEx。

答案 1 :(得分:1)

This two stage `Regexp` 
  1. hsus(ir%$%^t)bla dsd (g°ot)(rifk)转换为ir%$%^t g°ot rifk
  2. 一次性ir%$%^t g°ot rifkirt got rifk
  3. 测试子

    Sub Main()
        Dim strTest As String
        strTest = "hsus(ir%$%^t)bla dsd (g°ot)(rifk)"
        MsgBox GrabIt(strTest)
    End Sub
    

    主要

    Function GrabIt(strIn As String) As String
    Dim objRegex As Object
    Dim objRegMC As Object
    Dim objRegM As Object
    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
    .Pattern = "\((.*?)\)"
    .Global = True
        If .test(strIn) Then
        Set objRegMC = .Execute(strIn)
            For Each objRegM In objRegMC
            GrabIt = GrabIt & Chr(32) & objRegM.submatches(0)
            Next
        End If
    .Pattern = "[^\w|\s]+"
    GrabIt = .Replace(GrabIt, vbNullString)
    End With
    End Function