SRoy
SRoy

Reputation: 171

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.

Upvotes: 0

Views: 551

Answers (1)

armstrhb
armstrhb

Reputation: 4152

To close the Workbook:

wbk.Close

If you want to save the workbook beforehand, do:

wbk.Save
wbk.Close

Upvotes: 1

Related Questions