使用VBscript将word文档转换为excel

时间:2017-02-01 21:45:42

标签: excel vbscript ms-word

我正在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

1 个答案:

答案 0 :(得分:0)

看起来你真的不明白你在做什么......

Selection.Copy
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add()
ExcelSave = replace(files.path,"doc","xls")
objWorkbook.SaveAs(ExcelSave)

您制作了一个选择的副本,而不是将其粘贴到任何地方? Excel应该如何知道放在哪里? 您需要选择一个单元格并粘贴您刚刚复制的内容。当然,在退出Excel之前和保存之前,您需要执行此操作。