Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open File Without Calling Filepath

Tags:

excel

vba

I'm using excel VBA. I want to press a button that opens another file directly without the effect of "choosing file window".

This is the current code:

Sub loadFile_click()
Workbooks.Open("C:\Users\GIL\Desktop\ObsReportExcelWorkbook.xlsx")
End Sub

In this case, the file is in the same folder as the main file.

Is there any way to do it without entering the file's path?

like image 304
Gil Peretz Avatar asked May 04 '11 18:05

Gil Peretz


People also ask

What is the VBA code to open a file?

Steps to Open a Workbook using VBAType a dot (.) after that and select the Open method from the list. Specify the file path in the first argument and make sure to enclose it in double quotation marks. In the end, run the code to open the workbook.

How do I open a text file in Excel VBA?

Step 1: Open Excel. Step 2: Add a shape (Read Text File) to your worksheet . Step 3: Right-click on “Read Text file” and “Assign Macro..” Step 7: Adjust column width in your excel file.


2 Answers

If the file name is fixed you can use the ActiveWorkbook.Path function to return the path of the current workbook:

Dim FileName as string FileName = ActiveWorkbook.Path & "\myfile.xlsx

Check if you need that extra slash character.

like image 56
Simon Avatar answered Sep 23 '22 08:09

Simon


If the file is in the same folder as the document containing your VBA macro, use

ThisWorkbook.Path

for example:

Workbooks.Open(ThisWorkbook.Path & "\ObsReportExcelWorkbook.xlsx")

(this works even if the document is not the active one any more, or you changed the current directory).

like image 44
Doc Brown Avatar answered Sep 22 '22 08:09

Doc Brown