我需要在文档中找到特定的文本并获得段落编号位置
这是用于Excel VBA
Sub exportardatos()
'Paso 1: Declare las variables
Dim Paragraphe As Object, WordApp As Object, WordDoc As Object, WordTable As Object, WordRange As Object
File = "C:\Users\lper\Documents\FormExp.docx"
On Error Resume Next
'creationsession Word
Set WordApp = GetObject(class:="Word.Application")
'Clear the error between errors
Err.Clear
If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")
If Err.Number = 429 Then
MsgBox "Microsoft Word could not be found, aborting."
GoTo EndRoutine
End If
On Error GoTo 0
WordApp.Visible = True
WordApp.Activate
'open the file .doc
Set WordDoc = WordApp.Documents.Open(File)
'Word Enumerated Constants
Const wdReplaceAll = 2
WordApp.Documents("FormExp.docx").Activate
Dim nParag As Long
Set WordRange = WordApp.ActiveDocument.Paragraphs(1).Range
For Each WordRange In WordDoc.StoryRanges
With WordApp.Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "Legal"
.Wrap = wdFindContinue
.Execute
Do While .Execute = True
nParag = WordRange(0, Selection.Paragraphs(1).Range.End).Paragraphs.Count
MsgBox (nParag)
Loop
End With
Next WordRange
EndRoutine:
'Optimize Code
Application.ScreenUpdating = True
Application.EnableEvents = True
'Clear The Clipboard
Application.CutCopyMode = False
'Set WordDoc = Nothing
'Set WordApp = Nothing
MsgBox ("Ready")
End Sub
我收到代码错误438
答案 0 :(得分:2)
这是如何获取段落编号的快速示例。请注意,您无需Activate
Word文档即可使它工作。
Public Sub Exportardatos()
Dim filename As String
filename = "C:\Users\lper\Documents\FormExp.docx"
Dim wordApp As Object
Set wordApp = GetObject(class:="Word.Application")
If wordApp Is Nothing Then
Set wordApp = CreateObject(class:="Word.Application")
If Err.Number > 0 Then
MsgBox "Microsoft Word cannot be found!", vbOKOnly + vbCritical
Exit Sub
End If
End If
Dim wordDoc As Object
Dim searchRange As Object
Set wordDoc = wordApp.Documents.Open(filename)
Set searchRange = wordDoc.Range
With searchRange.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "Legal"
.Wrap = 0 '=wdFindStop
While .Execute(FindText:="Legal", Forward:=True)
If .found Then
Debug.Print "found in paragraph " & GetParNum(wordDoc, .Parent)
End If
Wend
End With
End Sub
Function GetParNum(ByRef doc As Object, ByRef r As Object) As Integer
'--- based on http://www.vbaexpress.com/kb/getarticle.php?kb_id=59
Dim rParagraphs As Object
Dim CurPos As Long
r.Select
CurPos = doc.Bookmarks("\startOfSel").Start
Set rParagraphs = doc.Range(Start:=0, End:=CurPos)
GetParNum = rParagraphs.Paragraphs.Count
End Function