如何通过Excel VBA代码在Word中抓取新行

gr8qqesn  于 2022-11-26  发布在  其他
关注(0)|答案(1)|浏览(177)

我有一段代码可以将Word文件的内容转换为一个变量,因此我解析了这些内容,并通过VBA代码处理这些内容。我的问题是:我目前正在循环扫描信件,但我不知道如何找到换行符。感谢您的帮助。这是我目前正在使用的代码

Sub open_word_find_text()

Dim book1 As Word.Application
Dim sheet1 As Word.Document
Set book1 = CreateObject("word.application")
book1.Visible = True

                GetFilePath = Application.GetOpenFilename   'Select a file'
                         Filename = Mid(GetFilePath, InStrRev(GetFilePath, "\") + 1, 999):
                        FilePath = Mid(GetFilePath, 1, InStrRev(GetFilePath, Filename) - 2)
 find_text = InputBox("Type the text you are looking for:")
     
file = Dir(FilePath & "\")

               While (file <> "")  'loop over all the files in the folder
                  
                  If InStr(file, ".docx") > 0 Then
              
                      Filename = Mid(file, InStrRev(file, "\") + 1, 999):
                      
                       Set sheet1 = book1.Documents.Open(FilePath & "\" & file)
                                                             
                            ff = sheet1.Content   'Save the contents of the file in a variable
                                  count_result = 0
                             For i = 1 To Len(ff)

                                  ff2 = Mid(ff, i, Len(find_text))
                                    
                                  If ff2 = find_text Then
                                    count_result = count_result + 1                                  
                                      MsgBox "Number result: " & count_result & vbNewLine & Mid(ff, i - 150, i + 200), vbOKCancel + vbMsgBoxRight + vbAbortRetryIgnore, Filename
                                  End If
                                    DoEvents
                             Next
b:
                  End If                   
                 sheet1.Close
                 file = Dir
                 DoEvents
              Wend
book1.Quit
MsgBox " end!"
End Sub
50pmv0ei

50pmv0ei1#

我不明白您要做什么,但下面的代码将通过在vbCr(表示换行符的常量)上进行拆分,将文档的内容存储在字符串数组中:

Dim sLinesArr() As String
sLinesArr = Split(sheet1.Content.Text, vbCr)

然后可以在循环中使用该数组:

Dim vLine As Variant

For Each vLine In sLinesArr
    MsgBox vLine
Next

相关问题