如果你需要将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编辑器中,通过点击“工具”→“引用”来勾选。