简体   繁体   中英

How can I code to close an open workbook using its directory path instead of its name using vba in excel?

So I've written a script that opens a certain workbook using its directory pathway (through text from a userform textbox) and I want to be able to close it at the end of the script. My script currently opens a workbook using the file directory and copies something from that workbook and pastes it into the current workbook. The only thing I want to add is that workbook closing at the end of the sub.

Sub A()

    Dim wbk As Workbook
    strFirstFile = Userform1.Command.Text
    Set wbk = Workbooks.Open(strFirstFile)
    With wbk.Sheets("Sheet1")
    Range("A1").Select
        Range(Selection, Selection.End(xlDown)).Select
        Range(Selection, Selection.End(xlToRight)).Select
        Selection.Copy
    End With
    Set wbk = ThisWorkbook
    wbk.Sheets("dog").Range("A1").Insert

End Sub

Bear with me I'm a super newbie.

To close the Workbook:

wbk.Close

If you want to save the workbook beforehand, do:

wbk.Save
wbk.Close

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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