简体   繁体   中英

Excel VBA-How to open a file in a folder which will be stored in a different directory?

I want to know how to open files inside one folder without having to specify the full path (C:\\Users[username]\\Desktop\\DBMacro\\csv\\folder2)

The folder name is DBMacro and I want excel to open my file even in these varying conditions:

1.The folder is not stored in the desktop.

  1. The folder is not on drive C:.

  2. My username is different.

  3. The DBMacro folder is stored in another folder.

Currently, I have two files inside this DBMacro folder. Let's name them file1 and file2. file1 is located directly inside DBMacro folder but file2 is located in a subfolder inside DBMacro.

I have tried doing this code

     Dim generalPath As String
     generalPath = ActiveWorkbook.path

but when I have to open both files later on,

     Workbooks.Open (generalPath & (subfolder) & "file1.csv")
     Workbooks.Open (generalPath & "file2.csv")

a problem occurs because whenever I try to open different workbooks, the value of ActiveWorkbook.path changes thus resulting to a buggy code.

I want to open both file1 and file2 wherein generalPath variable is still equal to the DBMacro folder path(which will change depending on where the folder is located)

Hoping for advice!

Change ActiveWorkbook.Path to ThisWorkbook.Path .

ThisWorkbook will always refer to the workbook that contains the code itself, whether it's active or not. Thus you can ensure that the path will never change (as long as you don't save to a new directory).

Application.ThisWorkbook Property (Excel)

Syntax

expression . ThisWorkbook

expression A variable that represents an Application object.

Remarks

Use this property to refer to the workbook that contains your macro code. ThisWorkbook is the only way to refer to an add-in workbook from inside the add-in itself. The ActiveWorkbook property doesn't return the add-in workbook; it returns the workbook that's calling the add-in.

The Workbooks property may fail, as the workbook name probably changed when you created the add-in. ThisWorkbook always returns the workbook in which the code is running.


For example, use code such as the following to activate a dialog sheet stored in your add-in workbook.

ThisWorkbook.DialogSheets(1).Show

This property can be used only from inside Microsoft Excel. You cannot use it to access a workbook from any other application.

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