如何在VBA中查找字符和数字之间的单词

时间:2015-01-13 06:59:18

标签: vba

例如,我有一个读取"IRS150Sup2500Vup"的字符串。它也可以是"IRS250Sdown1250Vdown"

在我以前的qn中,我问过如何找到2个字符之间的数字。现在,我需要在第二个S之后向上或向下找到这个词。由于它出现在角色S和数字之间,我该怎么做?

我的代码如下所示:

Dim pos, pos1,pos2 strString As String
pos = InStr(1, objFile.Name, "S") + 1
pos1 = InStr(pos, objFile.Name, "S")
pos2 = InStr(pos1, objFile.Name, ?)

pos1返回第二个S的索引。我不知道该放什么?

1 个答案:

答案 0 :(得分:1)

使用Regex

注意:您需要引用MS VBScripts正则表达式库。

Dim r As VBScript_RegExp_55.RegExp
Dim sPattern As String, myString As String
Dim mc As VBScript_RegExp_55.MatchCollection, m As VBScript_RegExp_55.Match

myString = "IRS150Sup2500Vup"
sPattern = "\w?up+" 'searches for Sup, Vup, etc.
Set r = New VBScript_RegExp_55.RegExp
r.Pattern = sPattern

Set mc = r.Execute(myString)
For Each m In mc ' Iterate Matches collection.
    MsgBox "word: '" & m.Value & "' founded at: " & m.FirstIndex & " length: " & m.Length
Next

有关详细信息,请参阅:
How To Use Regular Expressions in Microsoft Visual Basic 6.0
Find and replace text by using regular expressions (Advanced)