这不太有效,我将文本选择为 Ok 但需要将其读入变量。
Sub findTest()
Dim firstTerm As String
Dim secondTerm As String
Dim myRange As Range
Dim selRange As Range
Dim selectedText As String
Set myRange = ActiveDocument.Range
firstTerm = "<patientFirstname>"
secondTerm = "</patientFirstname>"
With myRange.Find
.Text = firstTerm
.MatchWholeWord = True
.Execute
myRange.Collapse direction:=wdCollapseEnd
Set selRange = ActiveDocument.Range
selRange.Start = myRange.End
.Text = secondTerm
.MatchWholeWord = True
.Execute
myRange.Collapse direction:=wdCollapseStart
selRange.End = myRange.Start
selectedText = selRange.Select
End With
End Sub
Run Code Online (Sandbox Code Playgroud)
我试图从一个小的伪 xml 数据包中提取数据,因此搜索字符串在每个 word 文档中只会出现一次。
你的问题引出了几个更关键的问题:
但是,关于面值的问题,我将假设您有一个与此类似的文档:
<patientFirstname>Bob</patientFirstname>
<patientFirstname>Sally</patientFirstname>
Run Code Online (Sandbox Code Playgroud)
并且您想提取所有患者的名字。
您可能会发现以下代码比您发布的更简单:
Sub findTest()
Dim firstTerm As String
Dim secondTerm As String
Dim myRange As Range
Dim documentText As String
Dim startPos As Long 'Stores the starting position of firstTerm
Dim stopPos As Long 'Stores the starting position of secondTerm based on first term's location
Dim nextPosition As Long 'The next position to search for the firstTerm
nextPosition = 1
'First and Second terms as defined by your example. Obviously, this will have to be more dynamic
'if you want to parse more than justpatientFirstname.
firstTerm = "<patientFirstname>"
secondTerm = "</patientFirstname>"
'Get all the document text and store it in a variable.
Set myRange = ActiveDocument.Range
'Maximum limit of a string is 2 billion characters.
'So, hopefully your document is not bigger than that. However, expect declining performance based on how big doucment is
documentText = myRange.Text
'Loop documentText till you can't find any more matching "terms"
Do Until nextPosition = 0
startPos = InStr(nextPosition, documentText, firstTerm, vbTextCompare)
stopPos = InStr(startPos, documentText, secondTerm, vbTextCompare)
Debug.Print Mid$(documentText, startPos + Len(firstTerm), stopPos - startPos - Len(secondTerm))
nextPosition = InStr(stopPos, documentText, firstTerm, vbTextCompare)
Loop
MsgBox "I'm done"
End Sub
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22427 次 |
| 最近记录: |