Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA how do i open another workbook?

Tags:

excel

vba

I am trying to open another workbook, using the code below

Sheets("Range").Activate
   Range("A1").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    Workbooks.Open ("AvgStdev.xlsm")

And it was working before, but now excel is prompting the file cant be found. Help please :/

like image 797
user3457548 Avatar asked Feb 13 '23 15:02

user3457548


1 Answers

You can do what you want easily if you declare your variable as discussed HERE.
So if we are to apply it, you can open your workbook like this:

    Dim wb As Workbook
    Dim myfilename As String

    myfilename = "C:\Users\Ayaz\Desktop\Analysis\AvgStdev.xlsm"
    '~~> open the workbook and pass it to workbook object variable
    Set wb = Workbooks.Open(myfilename) 

    '~~> More codes here

Now later in your code if you are saving the same file:

    wb.Save '~~> save
    wb.Close '~~> close

Or you can do it using Close method only:

    wb.Close True '~~> explicit SaveChanges argument to true

Now if however you like to save it as another file:

    Dim newfilename As String
    newfilename = "C:\Users\Ayaz\Desktop\Analysis\Another.xlsm"
    '~~> If you are saving it in a format other than .xlsx,
    '~~> you have to be explicit in the FileFormat argument
    wb.SaveAs newfilename, xlOpenXMLWorkbookMacroEnabled
    wb.Close

HTH.

like image 106
L42 Avatar answered Feb 19 '23 14:02

L42