【发布时间】:2017-02-01 21:45:41
【问题描述】:
我正在用 VBscript 构建一个工具,可以将文件夹中的所有 word 文档转换为 excel 文档。我需要复制所有内容并保留源格式。这可以通过 ctrl-a 手动操作 word 文档并粘贴到 excel 文档中。主要问题是 ActiveDocument(我不确定它是否正在激活我的 word 文档),并且我不确定如何粘贴到 excel 文档中。
到目前为止,这是我的代码。它会生成与 word 文档同名的新 excel 文件,但不会复制内容并粘贴。
set shApp = CreateObject("shell.application")
currentPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")
set shFolder = shApp.NameSpace( currentPath )
set files = shFolder.Items()
for each files in files
if files.type = "Microsoft Word 97 - 2003 Document" OR files.type = "Microsoft Word Document" then
msgbox("Converting: "&files.path)
Call DocConvert() 'function call to function that converts .doc to .xls
end if
next
'Opens a word document copies the contents and pastes it into an excel document of the same name
Function DocConvert()
On Error Resume Next
Set objWord = GetObject(, "Word.Application")
If Err <> 0 Then
Set objWord = CreateObject("Word.Application")
End If
objWord.Visible = True
objWord.Documents.Open(files.path)
ActiveDocument.Range(0, 0).Select
Selection.WholeStory
Selection.Copy
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add()
ExcelSave = replace(files.path,"doc","xls")
objWorkbook.SaveAs(ExcelSave)
objWord.Quit
objExcel.Quit
End Function
【问题讨论】:
-
Word 文件是文档。 Excel 文件是电子表格。这感觉太不对劲了。
-
嗯,为什么在 Excel 中需要这些?也许这是XY Problem?将Word文本放入Excel的目的是什么?
-
for each files in files这不对...为什么不将file对象作为参数传递给DocConvert呢? -
On Error Resume Next- 一旦您引用了 Word,您应该使用On Error Goto 0取消此操作,否则您将看不到其他错误。