Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving an Excel sheet in a current directory with VBA

Tags:

excel

vba

I have created a sheet in vba Excel. I would like to save it the current directory, but not in absolute path, then, when this is executed somewhere else, there won't be problem.

Can somebody help ?

like image 447
Ndiol Dia Avatar asked Dec 21 '10 09:12

Ndiol Dia


People also ask

How do I save an Excel file using VBA?

VBA Save Workbook – Example #1Click on Insert tab > select Module. Step 2: Now write the subprocedure for the VBA Save workbook or we can choose any name to define it. Step 3: Now to select the current workbook, use Active workbook as shown below followed by a dot. Step 4: Search Save function from the list.

Can a macro save a file?

Save a file to a network drive programmatically in Excel Additionally, you can use a Microsoft Visual Basic for Applications macro to save the active workbook and use a variable for the file name.


2 Answers

I am not clear exactly what your situation requires but the following may get you started. The key here is using ThisWorkbook.Path to get a relative file path:

Sub SaveToRelativePath()
    Dim relativePath As String
    relativePath = ThisWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
    ActiveWorkbook.SaveAs Filename:=relativePath
End Sub
like image 61
Alex P Avatar answered Nov 09 '22 05:11

Alex P


VBA has a CurDir keyword that will return the "current directory" as stored in Excel. I'm not sure all the things that affect the current directory, but definitely opening or saving a workbook will change it.

MyWorkbook.SaveAs CurDir & Application.PathSeparator & "MySavedWorkbook.xls"

This assumes that the sheet you want to save has never been saved and you want to define the file name in code.

like image 31
Dick Kusleika Avatar answered Nov 09 '22 03:11

Dick Kusleika