简体   繁体   English

从VBA中的Word文件创建Excel文件

[英]Creating an Excel File from a Word File in VBA

currently I am trying to create a macro in word that when run it looks for a few "keywords" in the document (that are essentially just titles), copy the paragraph below these keywords & then create an Excel file and paste them into separate cells in this new file, obviously saving the file once done. 当前,我正在尝试创建一个宏,以使其在运行时会在文档中查找一些“关键字”(本质上只是标题),复制这些关键字下方的段落,然后创建一个Excel文件并将其粘贴到单独的单元格中在这个新文件中,显然一旦完成就保存文件。

Currently my code is as follows: 目前,我的代码如下:

Sub WordToExcel()

Dim ObjExcel As Object, ObjWorkBook As Object, ObjWorksheet As Object

Set ObjExcel = CreateObject("EXCEL.APPLICATION")
Set ObjWorkBook = ObjExcel.Workbooks.Open("C:\Users\john\Desktop\test.xlsx")
Set ObjWorksheet = ObjWorkBook.Worksheets("Sheet1")

With Selection.Find
    .ClearFormatting
    .Text = "Description"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
End With
Selection.Find.Execute
Selection.MoveDown Unit:=wdParagraph, Count:=1
Selection.MoveDown Unit:=wdParagraph, Count:=1, Extend:=wdExtend

Do Until Left(Selection.Text, Len(Selection.Text) - 1) = "Tasks and Timeframe"
    Ctr = Ctr + 1
    Selection.MoveDown Unit:=wdParagraph, Count:=1
    Selection.MoveDown Unit:=wdParagraph, Count:=1, Extend:=wdExtend
Loop

Selection.Copy
ActiveSheet.Paste
ActiveWorkbook.Save

ObjWorkBook.Save
ObjWorkBook.Close
Set ObjWorksheet = Nothing
Set ObjWorkBook = Nothing
ObjExcel.Quit
Set ObjExcel = Nothing

End Sub

and the word document that the macro is contained in is essentially just: 宏所包含的单词document本质上就是:


Description 描述

Here is the general description of this document. 这是本文档的一般说明。 This should be copied & pasted into the new excel file. 应该将其复制并粘贴到新的excel文件中。

Tasks and Timeframe 任务和时间表

Here are the tasks/the necessary timeframe. 这是任务/必要的时间范围。 This should also be copied & pasted into the Excel file. 这也应该复制并粘贴到Excel文件中。

Solution: This is working for me: 解决方案:这对我有用:

(1) Remove the loop Do Until ........ Loop . (1)删除循环Do Until .......... Loop The code before that already selects the paragraph you want to copy. 之前的代码已经选择了要复制的段落。

(2) Change (2)变更

ActiveSheet.Paste
ActiveWorkbook.Save

to

ObjWorksheet.Paste
ObjWorkBook.Save

Otherwise, your Word macro doesn't know which Excel sheet you are referring to. 否则,您的Word宏将不知道您要引用哪个Excel工作表。

Result: This is what the Excel file looks like after running the macro. 结果:这是运行宏后Excel文件的外观。

在此处输入图片说明

Note: I assume that down the road, you will want to put the sentences from the Word file into specific cells in Excel and not A1 as your code is doing now. 注意:我假设您将要把Word文件中的句子放在Excel中的特定单元格中,而不是A1因为您的代码正在这样做。 To accomplish that, add ObjWorksheet.Range("B2").Select (setting the cell to the desired target cell) before ObjWorksheet.Paste . 为了实现这个目标,添加ObjWorksheet.Range("B2").Select (将小区设置到所需靶细胞)之前ObjWorksheet.Paste

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM