使用Word vba脚本关闭特定窗口

时间:2013-04-03 16:31:13

标签: vb.net vba ms-word window

我创建了这段vb代码,提示在word中打开特定文件,修改它然后将其保存到特定位置。我希望能够关闭两个窗口,即单词宏文件窗口和保存的文档窗口。

Private Sub Document_Open()

adresse_debut = ActiveDocument.Path

    With Application.FileDialog(msoFileDialogOpen)
        .AllowMultiSelect = False

        .InitialView = msoFileDialogViewDetails
        .Title = "Select Text File"
        .InitialFileName = adresse_debut
        .Show


        If .SelectedItems.Count = 1 Then
            bingo = .SelectedItems(1)
        Else
            MsgBox ("Error")
         Exit Sub
        End If
    End With

Documents.Open FileName:=bingo

adresse = ActiveDocument.Path & "\"
Nom = ActiveDocument.Name
Nom = Left(Nom, Len(Nom) - 4) & "_Ready.txt"

Selection.TypeParagraph
Selection.TypeText Text:="hello"

ActiveDocument.SaveAs FileName:=adresse & Nom, FileFormat:=wdFormatText

ActiveWindow.Close
End Sub

1 个答案:

答案 0 :(得分:2)

创建相关对象并使用它们,而不是使用ActiveWindow / ActiveDocument。见这个例子。

Private Sub Document_Open()
    Dim Doc1 As Document, Doc2 As Document

    Set Doc1 = ActiveDocument

    adresse_debut = Doc1.Path

    With Application.FileDialog(msoFileDialogOpen)
        .AllowMultiSelect = False

        .InitialView = msoFileDialogViewDetails
        .Title = "Select Text File"
        .InitialFileName = adresse_debut
        .Show

        If .SelectedItems.Count = 1 Then
            bingo = .SelectedItems(1)
        Else
            MsgBox ("Error")
            Exit Sub
        End If
    End With

    Set Doc2 = Documents.Open(FileName:=bingo)

    adresse = Doc2.Path & "\"
    Nom = Doc2.Name
    Nom = Left(Nom, Len(Nom) - 4) & "_Ready.txt"

    Selection.TypeParagraph
    Selection.TypeText Text:="hello"

    Doc2.SaveAs FileName:=adresse & Nom, FileFormat:=wdFormatText

    Doc2.Close SaveChanges:=False
    Doc1.Close SaveChanges:=False
End Sub