? ? ?如果你需要將Word文檔的內容導入Excel工作表來進行數據加工,使用下面的代碼可以實現:
Sub ImportWordToExcel()Dim wordApp As Word.ApplicationDim wordDoc As Word.DocumentDim excelSheet As WorksheetDim filePath As VariantDim i As LongDim para As Word.ParagraphDim lineText As String' 設置Excel工作表Set excelSheet = ThisWorkbook.Sheets("Sheet1") ' 修改為你的工作表名稱i = 1 ' 從A1開始寫入' 讓用戶選擇Word文檔filePath = Application.GetOpenFilename("Word Documents (*.docx;*.doc), *.docx", , "選擇要導入的Word文檔")If filePath = False Then Exit Sub ' 用戶取消選擇On Error GoTo ErrorHandler' 創建Word應用Set wordApp = New Word.ApplicationwordApp.Visible = False ' 隱藏Word界面' 打開Word文檔Set wordDoc = wordApp.Documents.Open(filePath)' 遍歷每個段落For Each para In wordDoc.ParagraphslineText = Replace(para.Range.Text, Chr(13), "") ' 移除段落標記lineText = Trim(lineText)If lineText <> "" Then' 可選:按手動換行符分割行(例如Shift+Enter)Dim lines As Variantlines = Split(lineText, Chr(11)) ' Chr(11)代表手動換行符For Each line In linesIf Trim(line) <> "" ThenexcelSheet.Cells(i, 1).Value = Trim(line)i = i + 1End IfNext lineEnd IfNext paraCleanup:' 關閉并釋放Word對象If Not wordDoc Is Nothing ThenwordDoc.Close SaveChanges:=FalseSet wordDoc = NothingEnd IfIf Not wordApp Is Nothing ThenwordApp.QuitSet wordApp = NothingEnd IfExit SubErrorHandler:MsgBox "錯誤 " & Err.Number & ": " & Err.Description, vbCritical, "錯誤"Resume Cleanup
End Sub
? ? ? ? 注意:使用以上代碼需要引用“Microsoft Word xx.0 Object Library”庫,在Excel VBA編輯器中,通過點擊“工具”→“引用”來勾選。