Say, I’m writing a VBA inside my excel file sample.xls. Now I want to get the full path of sample.xls in my VBA. How do I do it?
asked Dec 13, 2009 at 5:12
2
If you mean VBA, then you can use FullName, for example:
strFileFullName = ThisWorkbook.FullName
(updated as considered by the comments: the former used ActiveWorkbook.FullName
could more likely be wrong, if other office files may be open(ed) and active. But in case you stored the macro in another file, as mentioned by user @user7296559 here, and really want the file name of the macro-using file, ActiveWorkbook
could be the correct choice, if it is guaranteed to be active at execution time.)
answered Dec 13, 2009 at 9:57
FionnualaFionnuala
90.1k7 gold badges110 silver badges148 bronze badges
3
this is a simple alternative that gives all responses, Fullname, Path, filename.
Dim FilePath, FileOnly, PathOnly As String
FilePath = ThisWorkbook.FullName
FileOnly = ThisWorkbook.Name
PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))
answered Mar 13, 2017 at 9:44
APWAPW
2913 silver badges3 bronze badges
1
strScriptFullname = WScript.ScriptFullName
strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,""))
answered Dec 13, 2009 at 5:18
Mitch WheatMitch Wheat
294k43 gold badges465 silver badges540 bronze badges
1
If you need path only this is the most straightforward way:
PathOnly = ThisWorkbook.Path
lucascaro
15.9k3 gold badges37 silver badges47 bronze badges
answered Oct 27, 2018 at 5:39
LouisLouis
392 bronze badges
if you need path only without file name:
ActiveWorkbook.Path
it would return D:Folder
if you need file path with file name also:
ActiveWorkbook.FullName
it would return D:Foldersample.xls
if you need file name only:
ActiveWorkbook.Name
it would return sample.xls
so if you want combine file path and file name to get full directory don’t forget to add «» between. otherwise its simpler using .Path
Reeno
5,69911 gold badges39 silver badges50 bronze badges
answered Mar 17, 2021 at 4:17
ActiveWorkbook.FullName would be better I think, in case you have the VBA Macro stored in another Excel Workbook, but you want to get the details of the Excel you are editing, not where the Macro resides.
If they reside in the same file, then it does not matter, but if they are in different files, and you want the file where the Data is rather than where the Macro is, then ActiveWorkbook is the one to go for, because it deals with both scenarios.
Emil
7,20117 gold badges77 silver badges134 bronze badges
answered Dec 14, 2016 at 12:41
There is a universal way to get this:
Function FileName() As String
FileName = Mid(Application.Caption, 1, InStrRev(Application.Caption, "-") - 2)
End Function
answered May 15, 2018 at 16:46
1
Mojakhed 0 / 0 / 0 Регистрация: 23.10.2012 Сообщений: 13 |
||||||||
1 |
||||||||
Как получить путь к файлу и имя этого файла в переменные23.10.2012, 11:58. Показов 89764. Ответов 22 Метки нет (Все метки)
Добрый день, Задача проста, есть решение, но оно не изящное, хотелось бы оптимизировать код. Все делается в VBA Excel 2010. 1. Получаем Имя файла
2. Получаем Путь к файлу (код не мой, помог Гугл)
Заранее спасибо
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
23.10.2012, 11:58 |
22 |
Казанский 15136 / 6410 / 1730 Регистрация: 24.09.2011 Сообщений: 9,999 |
||||
23.10.2012, 12:17 |
2 |
|||
fName в первом коде — полный путь к файлу. Вы хотите разделить его на путь к папке и имя?
2 |
0 / 0 / 0 Регистрация: 23.10.2012 Сообщений: 13 |
|
23.10.2012, 15:18 [ТС] |
3 |
Благодарю, вопрос исчерпан.
0 |
Hugo121 6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
||||
23.10.2012, 17:30 |
4 |
|||
Так попробуйте в первом коде:
Получите «полный путь к этому файлу, а так же его имя в отдельные переменные».
0 |
0 / 0 / 0 Регистрация: 23.10.2012 Сообщений: 13 |
|
23.10.2012, 19:14 [ТС] |
5 |
To Hugo121 Наверное я не достаточно четко сформулировал задачу, в любом случае, Казанский помог с решением проблемы. Я получил что хотел. В следующий раз буду четко формулировать. Спасибо.
0 |
Hugo121 6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
||||
23.10.2012, 20:55 |
6 |
|||
Ну когда есть полный путь и имя — легко от полного пути отрезать на длину имени…
0 |
rattrapper foo(); 886 / 587 / 222 Регистрация: 03.07.2013 Сообщений: 1,549 Записей в блоге: 2 |
||||||||
09.07.2013, 16:29 |
7 |
|||||||
нужна помощь, у меня код не работает(exel’13)
Импорт модуля проекта из файла
у меня нужные модули находятся в том же месте, что и книга, но я никак не могу получить полный путь к книге программно!
Добавлено через 36 минут
никак не могу получить полный путь к книге программно как же все просто)
0 |
ExpressFX 2 / 2 / 0 Регистрация: 24.10.2015 Сообщений: 1 |
||||
24.01.2016, 18:54 |
8 |
|||
Пути к файлу и имя файла — просто как 2+2 !
Выйдет сообщение:
2 |
4 / 4 / 0 Регистрация: 29.06.2015 Сообщений: 17 |
|
29.01.2016, 13:41 |
9 |
ActiveWindow.Caption возвращает имя открытого окна, т.е. имя файла без расширения.
0 |
Казанский 15136 / 6410 / 1730 Регистрация: 24.09.2011 Сообщений: 9,999 |
||||
29.01.2016, 15:20 |
10 |
|||
Федоров, …если заголовок окна не поменяли
0 |
0 / 0 / 0 Регистрация: 07.09.2015 Сообщений: 4 |
|
18.03.2016, 14:08 |
11 |
доброго дня всем, подскажите, а как теперь получаемые ответы вывести в ячейку? и чтоб без диалогового окна? просто выбор файла, а результат в ячейке, а не в окне.
0 |
Hugo121 6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
||||
18.03.2016, 14:19 |
12 |
|||
Вместо Msgbox пишите
— получите вместо сообщения строку в ячейке.
1 |
0 / 0 / 0 Регистрация: 07.09.2015 Сообщений: 4 |
|
18.03.2016, 15:24 |
13 |
благодарю, то что надо Добавлено через 1 минуту
0 |
6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
|
18.03.2016, 16:12 |
14 |
Используете ДВССЫЛ()? Она не в всех формулах работает. Если всё равно используете макрос — так сразу и формируйте макросом полностью формулы, или вообще делайте всю работу макросом.
0 |
0 / 0 / 0 Регистрация: 07.09.2015 Сообщений: 4 |
|
21.03.2016, 07:20 |
15 |
ДВССЫЛ не успользую, а в макросах не силен совсем.
0 |
Hugo121 6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
||||||||
21.03.2016, 09:22 |
16 |
|||||||
Попробуйте после замены файла
или
0 |
0 / 0 / 0 Регистрация: 07.09.2015 Сообщений: 4 |
|
21.03.2016, 11:04 |
17 |
нет, не работает ни в теле первого макроса, ни с отдельной кнопки((
0 |
6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
|
21.03.2016, 11:30 |
18 |
Попробуйте так — копируете любой файл клиента под именем например шаблон.xls, настраиваете все нужные формулы на импорт из этого файла.
0 |
Ivan_Ivanovich 0 / 0 / 0 Регистрация: 01.02.2016 Сообщений: 29 |
||||||||
14.04.2016, 09:59 |
19 |
|||||||
Здравствуйте, а подскажите пожалуйста как сделать так, чтобы можно было просто выбирать файл через диалоговое окно, не указывая при этом путь к файлу и само название файла. Нужно, чтобы была возможность выбрать любой файл на компьютере .xlsx и далее с ним работать (импортировать из него).
А вот продолжение кода в форме, при помощи которого 100% идет выбор файла (только автоматически, по прописанному пути и файлу, а нужно, чтобы можно было любой файл выбрать, чтобы не был заранее прописан код для файла) и уже выполнялась работа с ним.
0 |
6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
|
14.04.2016, 10:04 |
20 |
Т.е. не пробовали то, что я предлагаю?
0 |
VBA Get Workbook Path in Excel. We deal with multiple workbooks at a time. We may want to know Workbook path and its location. In the following tutorial we will learn to get Workbook complete Path and location using Path and FullName properties of Workbook.
Table of Contents:
- Objective
- Syntax to get complete path in Excel VBA
- Macro to Get path of the active Workbook in Excel
- VBA Code to Get Location of the current Workbook in Excel
- Instructions to Run VBA Macro Code
- Other Useful Resources
Syntax to Get complete Path of the Workbook in Excel VBA
Here is the syntax of to Get Path of the Workbook in Excel VBA.
expression.Path
Where expression represents Workbook object.
Path represents a property of Workbook. It returns Workbook complete Workbook path.
Macro to Get Path of the Workbook in Excel VBA
Let us see the following macro to get path of the active Workbook in Excel VBA.
'VBA Get path of the active Workbook in Excel Sub VBA_Get_ActiveWorkbook_Path() 'Variable declaration Dim sWorkbookPath As String sWorkbookPath = ActiveWorkbook.Path MsgBox "Active Workbook Path is : " & sWorkbookPath, vbInformation, "VBAF1" End Sub
Here is the output screenshot of above macro.
VBA Code to Get Location of the current Workbook in Excel
Here is the following VBA Code to Get Location of the current Workbook in Excel.
'VBA Get Location of the current Workbook in Excel Sub VBA_Get_CurrentWorkbook_Location() 'Variable declaration Dim sWorkbookLocation As String sWorkbookLocation = ThisWorkbook.FullName MsgBox "Current Workbook Location is : " & sWorkbookLocation, vbInformation, "VBAF1" End Sub
Let us see the output screenshot of above VBA code.
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions.
Instructions to run VBA Macro Code
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
VBA Tutorial VBA Functions List VBA Arrays in Excel Blog
VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers
Approach using Filter()
and one Split()
action
In addition to @Vityata ‘s answer I demonstrate an array alternative
accepting also vbNullString
as FullPath
argument.
Based on the same idea to make disappear the last split token, this approach doesn’t calculate item lengths, but removes the last item directly via Filter(a, a(Ubound(a)), False)
.
Function getPath(FullPath As String, Optional Delim As String = "") As String
Dim a: a = Split(FullPath & "$", Delim)
getPath = Join(Filter(a, a(UBound(a)), False), Delim)
End Function
Side note to Split()
The addition of & "$"
to FullPath argument is necessary to make the last split item unique,
otherwise it would remove all NOC
tokens, not only the last item. So an Example call like
Debug.Print getPath("RootzTrash - No longer neededNOCNOC")
returns the wanted result RootzTrash - No longer neededNOC
.
If an empty string would be splitted, there won’t occur an error as the zero array boundaries (i.e. 1 item) «join» to another vbNullString
.
In this post, you will be learning how to get the full File Path and File name using Excel VBA in your Excel Spreadsheet.
The file path and file name using Excel VBA can be accessed using the ‘.Path’ and ‘.FullName‘ properties.
.Path Property
The Path property returns the complete, saved path of the workbook -Excel file.
How to Get File Name using Excel VBA?
.FullName Property
The FullName property returns the complete, saved path, including the name of the workbook.
Let’s see these properties with the help of an example.
- Create an Excel file and name it of your choice.
- Firstly, place a command button on your worksheet using the insert option in the Developer tab
Enter the following code in the VBA of the button:
MsgBox Workbooks("Developerpublish.com-Path and full name.xlsm.xlsm").Path
This returns the complete path to the current excel file.
MsgBox ActiveWorkbook.FullName
This line returns the complete path, including the name of the active workbook.
You need to enter the exact file name to find its path.