【问题标题】:Converting word documents to excel with VBscript使用VBscript将word文档转换为excel
【发布时间】: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 取消此操作,否则您将看不到其他错误。

标签: excel vbscript ms-word


【解决方案1】:

看起来你并没有真正理解你在做什么......

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 和保存之前执行此操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 2018-01-27
    • 1970-01-01
    • 2022-10-25
    • 2011-11-10
    • 1970-01-01
    • 2015-06-03
    相关资源
    最近更新 更多