繁体   English   中英

Excel VBA退出Word文档

[英]Excel VBA quit Word document

我有一个宏,将Excel文档的选择单元格插入Word模板,复制整个Word文档,然后关闭文档而不保存,以保留某些关键字。

但是,当它关闭Word文档时,它会打开一个空白的Word窗口,没有活动文档,每次运行宏时都会留下一个新的空白窗口。

Dim appWd As Word.Application
Dim wdFind As Object
Dim ClipEmpty As New MSForms.DataObject
Dim ClipT As String

Sub CopyDatatoWord()
    Dim docWD As Word.Document
    Dim sheet1 As Object
    Dim sheet2 As Object
    Dim saveCell1 As String
    Dim saveCell2 As String
    Dim saveCell3 As String
    Dim dir1 As String
    Dim dir2 As String

    date_example = Cells(Application.ActiveCell.Row, 3)

    Set appWd = CreateObject("Word.Application")
    appWd.Visible = True
    Set docWD = appWd.Documents.Open(ThisWorkbook.Path & "\template.docx")

    'Select Sheet where copying from in excel
    Set sheet1 = Sheets("Scheduling tracker")
    Set wdFind = appWd.Selection.Find

    Cells(Application.ActiveCell.Row, 15).Select
    Selection.Copy
    wdFind.Text = "QREQQ"
    Call NoFormatPaste

    Cells(Application.ActiveCell.Row, 14).Select
    Selection.Copy
    wdFind.Text = "QREQNOQ"
    Call NoFormatPaste

    Cells(Application.ActiveCell.Row, 6).Select
    Selection.Copy
    wdFind.Text = "QNAMEQ"
    Call NoFormatPaste

    Cells(Application.ActiveCell.Row, 15).Select
    Selection.Copy
    wdFind.Text = "QREQQ"
    Call NoFormatPaste

    Cells(Application.ActiveCell.Row, 14).Select
    Selection.Copy
    wdFind.Text = "QREQNOQ"
    Call NoFormatPaste

    Dim dateValue As String
    dateValue = Cells(Application.ActiveCell.Row, 3).Value
    wdFind.Text = "QDATEQ"
    Call NoFormatDatePaste(dateValue)

    Dim timeValue As String
    timeValue = Cells(Application.ActiveCell.Row, 4).Value
    wdFind.Text = "QTIMEQ"
    Call NoFormatTimePaste(timeValue)

    appWd.Selection.WholeStory
    appWd.Selection.Copy

    appWd.ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges

    Set appWd = Nothing
    Set docWD = Nothing
    Set appXL = Nothing
    Set wbXL = Nothing
End Sub

这是我剩下的窗口,每次运行宏时都会创建一个新窗口。

空白的Word窗口后宏

我试过用

appWd.Application.Quit SaveChanges:=wdDoNotSaveChanges

但这也将迫使任何其他打开的文档退出。 有没有人知道如何在不离开这个空白的应用程序窗口的情况下关闭文档?

请将以下内容添加到您的代码中:

appWd.Quit

这将介于两者之间

appWd.ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges

Set appWd = Nothing

这称为WinWord Quit方法,它可以解决您的问题。

我有同样的问题。 只有下面的代码关闭了这个Word窗口:

Dim x As Variant

X = Shell("powershell.exe kill -processname winword", 1)

我在其中一个答案中找到了这段代码。 从excel vba中关闭word应用程序

暂无
暂无

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

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