gpt4 book ai didi

excel - 如何在 Word VBA 中获取特定文本的段落号?

转载 作者:行者123 更新时间:2023-12-04 21:19:40 25 4
gpt4 key购买 nike

我需要在我的文档中找到特定文本并获取段落编号位置

这是用于 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

最佳答案

这是一个如何获取段落编号的快速示例。请注意,您不必 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

关于excel - 如何在 Word VBA 中获取特定文本的段落号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56529732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com