1

我创建了这段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
4

1 回答 1

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
于 2013-04-03T16:40:18.997 回答