Полный путь файла excel vba

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?

Community's user avatar

asked Dec 13, 2009 at 5:12

Veera's user avatar

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.)

Andreas Covidiot's user avatar

answered Dec 13, 2009 at 9:57

Fionnuala's user avatar

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

APW's user avatar

APWAPW

2913 silver badges3 bronze badges

1

   strScriptFullname = WScript.ScriptFullName 
   strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"")) 

answered Dec 13, 2009 at 5:18

Mitch Wheat's user avatar

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's user avatar

lucascaro

15.9k3 gold badges37 silver badges47 bronze badges

answered Oct 27, 2018 at 5:39

Louis's user avatar

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's user avatar

Reeno

5,69911 gold badges39 silver badges50 bronze badges

answered Mar 17, 2021 at 4:17

TheAccountant's user avatar

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's user avatar

Emil

7,20117 gold badges77 silver badges134 bronze badges

answered Dec 14, 2016 at 12:41

user7296559's user avatar

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

Riccardo La Marca's user avatar

1

Mojakhed

0 / 0 / 0

Регистрация: 23.10.2012

Сообщений: 13

1

Как получить путь к файлу и имя этого файла в переменные

23.10.2012, 11:58. Показов 89764. Ответов 22

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Добрый день,

Задача проста, есть решение, но оно не изящное, хотелось бы оптимизировать код. Все делается в VBA Excel 2010.
Необходимо выбирая случайный фаил получать полный путь к этому файлу, а так же его имя в отдельные переменные. У меня это получилось сделать только в 2 этапа, т.е 2 раза выводя диалоговое окно. Хотелось бы это делать за 1 диалог.

1. Получаем Имя файла

Visual Basic
1
2
3
4
Set fs = CreateObject("Scripting.FileSystemObject")
fName = Application.GetOpenFilename
s = fs.GetFileName(fName)
MsgBox s, vbInformation + vbOKOnly

2. Получаем Путь к файлу (код не мой, помог Гугл)

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Function GetFolderPath(Optional ByVal Title As String = "Select Folder", _
                       Optional ByVal InitialPath As String = "c:") As String
   Dim PS As String: PS = Application.PathSeparator
    With Application.FileDialog(msoFileDialogFolderPicker)
        If Not Right$(InitialPath, 1) = PS Then InitialPath = InitialPath & PS
        .ButtonName = "Select": .Title = Title: .InitialFileName = InitialPath
        If .Show <> -1 Then Exit Function
        GetFolderPath = .SelectedItems(1)
        If Not Right$(GetFolderPath, 1) = PS Then GetFolderPath = GetFolderPath & PS
    End With
End Function
 
Path = GetFolderPath
MsgBox Path, vbInformation + vbOKOnly

Заранее спасибо



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 в первом коде — полный путь к файлу. Вы хотите разделить его на путь к папке и имя?
Это можно сделать так:

Visual Basic
1
2
3
4
5
FullPath = Application.GetOpenFilename
i = InStrRev(FullPath, "") 'позиция последнего 
Name = Mid(FullPath, i + 1)
Folder = Left(FullPath, i - 1)
MsgBox FullPath & vbLf & Name & vbLf & Folder



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

Так попробуйте в первом коде:

Visual Basic
1
MsgBox fName & vbNewLine & s, vbInformation + vbOKOnly

Получите «полный путь к этому файлу, а так же его имя в отдельные переменные».



0



0 / 0 / 0

Регистрация: 23.10.2012

Сообщений: 13

23.10.2012, 19:14

 [ТС]

5

To Hugo121

Наверное я не достаточно четко сформулировал задачу, в любом случае, Казанский помог с решением проблемы. Я получил что хотел.
Под полным путем подразумевалось путь до файла без его имени, т.е «C:temp» в одну переменную и имя файла «asd.txt» в другую переменную.

В следующий раз буду четко формулировать. Спасибо.



0



Hugo121

6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

23.10.2012, 20:55

6

Ну когда есть полный путь и имя — легко от полного пути отрезать на длину имени…

Visual Basic
1
2
3
4
5
6
7
Sub tt()
    Set fs = CreateObject("Scripting.FileSystemObject")
    fname = Application.GetOpenFilename
    s = fs.GetFileName(fname)
    ss = Left(fname, Len(fname) - Len(s))
    MsgBox fname & vbLf & ss & vbLf & s, vbInformation, vbOKOnly
End Sub



0



rattrapper

foo();

886 / 587 / 222

Регистрация: 03.07.2013

Сообщений: 1,549

Записей в блоге: 2

09.07.2013, 16:29

7

нужна помощь, у меня код не работает(exel’13)
нашел отличный faq по добавлению модулей,

Цитата
Сообщение от Dragokas
Посмотреть сообщение

Импорт модуля проекта из файла

Visual Basic
1
ИмяПроекта.VBProject.VBComponents.Import *"Путь и ИмяФайла"

у меня нужные модули находятся в том же месте, что и книга, но я никак не могу получить полный путь к книге программно!
GetOpenFilename — в любом случае вызывает окно выбора файла
еще пробовал HKEY_CURRENT_USERDesktop — выдает ошибку
мой код:

Visual Basic
1
2
3
4
5
6
Sub AddMacro()
With ThisWorkbook.VBProject.VBComponents
    .Import "путь к книге???"  Module1.bas
    .Import "путь к книге???"  mw2.frm
End With
End Sub

Добавлено через 36 минут

Цитата
Сообщение от rattrapper
Посмотреть сообщение

никак не могу получить полный путь к книге программно

как же все просто)
кому нужно thisworkbook.path



0



ExpressFX

2 / 2 / 0

Регистрация: 24.10.2015

Сообщений: 1

24.01.2016, 18:54

8

Пути к файлу и имя файла — просто как 2+2 !

Visual Basic
1
2
3
4
5
6
7
Sub ShowPathAndName()
    Dim FullName$, Filename$, FilePath$
    FullName = "C:Worktest.txt"
    Filename = Dir(FullName) ' Сработает только если файл по указанному пути реально существует
    FilePath = Left(FullName, Len(FullName) - Len(Filename))
    MsgBox "Путь к файлу - " & FilePath & vbCrLf & "Имя файла - " & Filename
End Sub

Выйдет сообщение:
Путь к файлу — C:Work
Имя файла — test.txt

Просто и не нужно извращаться!



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

Федоров, …если заголовок окна не поменяли

Visual Basic
1
activewindow.Caption="Федоров"



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 пишите

Visual Basic
1
[A1]=

— получите вместо сообщения строку в ячейке.



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

ДВССЫЛ не успользую, а в макросах не силен совсем.
вот формула =[AW104]Данные!$B$18, по которой подтягиваются данные из внешних источников, а ячейка AW104 получает полный путь файла источника по вышеприведенному макросу.



0



Hugo121

6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

21.03.2016, 09:22

16

Попробуйте после замены файла

Visual Basic
1
 ActiveWorkbook.RefreshAll

или

Visual Basic
1
Calculate



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, настраиваете все нужные формулы на импорт из этого файла.
Сохраняете файл, ставите ему «только для чтения».
Удаляете шаблон.xls.
Юзер открывает файл с формулами, в диалоге обновления связей указывает файл нужного клиента. Посмотрел, если нужно сохранить — сохранил с любым другим именем.
Но можно конечно всё делать макросом — юзер жмёт кнопку, указывает файл, смотрит данные. Вообще всё без формул.



0



Ivan_Ivanovich

0 / 0 / 0

Регистрация: 01.02.2016

Сообщений: 29

14.04.2016, 09:59

19

Здравствуйте, а подскажите пожалуйста как сделать так, чтобы можно было просто выбирать файл через диалоговое окно, не указывая при этом путь к файлу и само название файла. Нужно, чтобы была возможность выбрать любой файл на компьютере .xlsx и далее с ним работать (импортировать из него).
При помощи данного кода открывается диалоговое окно, можно выбрать файл, но он как я понимаю не выбирается (не используется в дальнейшем как нужно мне). Я данный код превратил в комментарии и ничего не поменялось в работе.

PureBasic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Private Sub SelectStudent_Click()
 
Dim FName As String
Dim result As Integer
With Application.FileDialog(1)
   .Title = "Select file"
   .InitialFileName = "C:BD" 'default path Путь по умолчанию
   .AllowMultiSelect = False
   .Filters.Clear
   .Filters.Add "MS Excel", "*.xlsx", 1
result = .Show
 
If result = 0 Then Exit Sub
FName = Trim(.SelectedItems.Item(1))
End With

А вот продолжение кода в форме, при помощи которого 100% идет выбор файла (только автоматически, по прописанному пути и файлу, а нужно, чтобы можно было любой файл выбрать, чтобы не был заранее прописан код для файла) и уже выполнялась работа с ним.

PureBasic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Dim app As Object, wrk As Object
Dim rst As dao.Recordset
 
Set rst = CurrentDb.OpenRecordset("select * from Marks")
Set app = CreateObject("excel.application")
Set wrk = app.workbooks.Open("C:BDsample.xlsx")
 
rst.AddNew
 
rst![mrk_id] = Nz(DMax("mrk_id", "Marks"), 0) + 1
rst![Module] = Modul(app.range("A14"))
rst![Hours] = app.range("C15")
 
 
rst.Update
app.Quit
 
End Sub



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.

Workbook Path

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.

Workbook Location

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

How to Get File Name using Excel VBA?

 Enter the following code in the VBA of the button:

How to Get the File Path and File Name using Excel VBA?

MsgBox Workbooks("Developerpublish.com-Path and full name.xlsm.xlsm").Path

This returns the complete path to the current excel file.

How to Get the File Path and File Name using Excel VBA?

MsgBox ActiveWorkbook.FullName

This line returns the complete path, including the name of the active workbook.

How to Get the File Path and File Name using Excel VBA?

You need to enter the exact file name to find its path.

Понравилась статья? Поделить с друзьями:
  • Полный путь к ячейке excel
  • Полный видеокурс по excel
  • Полный алфавитный перечень excel
  • Полный адрес ячейки в excel это
  • Полные значения в excel