问题
In Word, when I select a paragraph, I need a MsgBox to display a list (i.e. a new line for each) of a certain section within an endnote.
The below code will display a MsgBox with the FULL TEXT of endnotes within the selection, but I only want the information between the phrase "Extracted material is from " and the next semicolon to be listed in the MsgBox. (Example below of endnotes with desired extraction in bold)
Endnote Format:
[1] Position1text; Position2text; Position3text; Position4text; Position5text; Position6 Extracted material is from EDIBLE//FRUIT//APPPLES; Position7text; Position8text
[2] Position1text; Position2text; Position3text; Position4text; Position5text; Position6 Extracted material is from NONEDIBLE//FURNITURE//CHAIR; Position7text; Position8text
I'd like the MsgBox to read:
This paragraph contains:
EDIBLE//FRUIT//APPPLES
NONEDIBLE//FURNITURE//CHAIR
Sub TestEndNoteMsg()
Dim e As Endnote
Dim str As String
For Each e In Selection.Endnotes
str = str & e.Range.Text
Next e
MsgBox str
End Sub
回答1:
This is not optimized so that you can better see how this works. You can just as easily nest the InStr
functions into a single line, but it gets a little hard to follow.
Below you can see that you first find the position of the phrase "Extracted material is from " and add 27 characters to the position (the length of the string - 1). That gives us the character position we want to start the extraction from.
Then using this position as a new starting point, find the next semi-colon and save that position in lngEnd
. Then transform str
to extract only the data you want.
Edit
Forgot the loop, I am protecting str
until the parsed string is created, then appending each element to the variable. I changed str
to e.Range.Text
to deal only with the current endnote processing and avoiding truncating the previous endnote.
Sub TestEndNoteMsg()
Dim e As Endnote
Dim str As String
Dim lngStart As Long
Dim lngEnd As Long
For Each e In Selection.Endnotes
lngStart = InStr(1, e.Range.Text, "Extracted material is from ", 1) + 27
lngEnd = InStr(lngStart, e.Range.Text, ";", 1)
str = str & MID(e.Range.Text, lngStart, lngEnd - lngStart) & vbcrlf
Next e
MsgBox "This paragraph contains:" & vbcrlf & str
End Sub
来源:https://stackoverflow.com/questions/47076277/extract-text-from-string-generated-from-selected-endnotes