簡體   English   中英

在word doc中查找唯一文本並從excel vba中從這個word doc中復制連續的字符串

[英]Find unique text in word doc and copy consecutive string from this word doc, from excel vba

我的目標是在單詞文檔“北愛爾蘭經濟”中找到唯一的文本,並從該文檔中復制三個連續的單詞。 我必須從excel VBA中做到這一點。 正在搜索的 word 文檔將在從 .xlsm 文件執行 VBA 代碼之前手動打開。 這將是 VBA 代碼執行時唯一打開的 .docx 文件,但文件名總是不同的,因此我們不能硬編碼 .docx 文件名或路徑。

Sub Find_Price()

    Dim WordApp As Word.Application
    Dim WordDoc As Word.Document
    Dim TextToFind As String
    Dim NumberToFind As String
    Dim Rng As Word.Range
    Application.ScreenUpdating = False
    'This is the text I'm looking for in .ActiveDocument
    TextToFind = "The economies of Northern Ireland "
    NumberToFind = "82110907192"
    'Reference already opened Word document from excel VBA console
    Set WordApp = GetObject(, "Word.Application")
    WordApp.Application.Visible = True
    WordDoc.Select
    Set Rng = WordApp.ActiveDocument.Content
    'Set WordDoc = WordApp.Documents.Open(FilePath & "Form1.docx")
    'Set WordDoc = WordApp.ActiveDocument     'I don't know how to finish this line  :-(
        'With WordApp.Content.Find.Execute.NumberToFind
        With WordDoc.Content.Find.Execute.NumberToFind     'Code crashes in this line;
        Rng.Find.Execute FindText:=TextToFind, Forward:=True
                'what this "Forward:=True" means??
        If Rng.Find.Found Then
            If Rng.Information(wdWithInTable) Then
               ' I don't know how to write this part of the code.
               ' Please don't remove my question again - I've researched 16h for this info.
               MsgBox "Price is " & TextToFind & " pln."
            End If
        Else
            MsgBox "Text was not found!"
        End If
End Sub

代碼在這一行崩潰:

With WordDoc.Content.Find.Execute.NumberToFind

在此處輸入圖片說明

對我來說最重要的是:

1)從excel vba編輯器對當前打開的word doc執行搜索,

2)在這個word文檔中找到唯一的文字=“北愛爾蘭的經濟”,

3) 並將此文本復制到剪貼板,以便我可以手動將其粘貼到我選擇的單元格中。

搜索范圍。

With Rng.Find
    .Text = "The economies of Northern Ireland "
    .Execute
    If .Found = True Then
        Rng.MoveEnd wdWord, 3
        Rng.Copy
    Else
        MsgBox "Not found"
    End If
End With

如果 word 文檔已經打開(並且您確定它每次都會打開),那么我只會懶惰地聲明變量。

Dim oDoc as Word.Document
Set oDoc = Word.ActiveDocument
Dim oRng as Word.Range
Set oRng = oDoc.Content

但這是我個人的看法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM