【问题标题】:Printing a word document from excel vba从excel vba打印word文档
【发布时间】:2016-12-01 03:30:57
【问题描述】:

以下代码在完成后应该让用户输入一个数字(这里它硬编码为 50,并且不关注特定行 - 它不输入数据);在工作表中查找特定的一行或多行,复制 word 文档的空白模板,将该数据以特定顺序输入到 word 文档中,然后打印 word 文档。

它试图做的下面的代码是,使用 excel,将位于 C:\original\path\here 的 word 文档复制到 C:\original\path\there。不幸的是,每次我尝试在 Microsoft excel 中运行它时,Excel 都会挂起,然后我必须重新启动它。

那为什么?需要做什么? VBA 编辑器中引用了 Microsoft word Object Library 14。

 Sub UpdateActionsRows()

    Dim userInput As Long
    userInput = 50

' set up word application, document
    Dim objWord As Word.Application
    Dim objDoc As Document

    Set objWord = CreateObject("Word.Application")
    Set objDoc = objWord.Documents.Open("C:\original\path\here")

    copyFile objDoc, userInput

    objDoc.Close
    objWord.Quit
End Sub

复制文件

Function copyFile(sourceFile As Document, inputRows As Long)
    Dim fso As Object
    Set fso = VBA.CreateObject("Scripting.FileSystemObject")

    Dim targetFile As String
    targetFile = "C:\original\file\there.docx" 
    fso.copyFile sourceFile, targetFile

End Function

【问题讨论】:

  • 您尝试复制的文件已经打开。您要么需要在打开之前复制,要么使用“另存为”。
  • @WayneG.Dunn 用 7 秒击败了我 :)
  • wayne G dunn 说得对。
  • 如果你继续使用你自己的copyFileSub(我拒绝称它为Function,因为你没有返回值!),你还需要更改@987654326 @ 到 fso.copyFile sourceFile.FullName, targetFile 因为在这种情况下 sourceFile 的默认属性只是 .Name 属性(即没有路径)。
  • P.S.将sourceFile 更改为sourceFile.FullName 实际上会允许您的代码工作(尽管文件已打开),但几乎可以肯定这不是您想要发生的事情。 (当然,假设 "C:\original\path\here" 实际上是 Word 文档的名称,而不仅仅是路径。)

标签: vba excel


【解决方案1】:

试试这样的:

 Sub UpdateActionsRows()

    Dim userInput As Long
    userInput = 50

' set up word application, document
    Dim objWord As Word.Application
    Dim objDoc As Document

    Set objWord = CreateObject("Word.Application")
    Set objDoc = objWord.Documents.Open("C:\original\path\here")
    objDoc.Close

    FileCopy objDoc, "C:\original\path\there"
    objWord.Quit
End Sub

我还没有测试过它,它可以写得更好,但希望它可以工作。作为@Wayne G. Dunn,错误是因为您试图复制打开的文件。在这里你可能会看到更多 - VBA to copy a file from one directory to another

【讨论】:

  • 一旦你执行了objDoc.Close,你将无法在FileCopy命令中使用它的Name属性(或者,更好的是,它的FullName属性)。
猜你喜欢
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多