Vba excel адрес файла

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

VBA has some useful functions that can take your automation in Excel to the next level.

One such function is the VBA DIR function.

While by itself, it may seem like a simple function that does one specific thing.

But when you combine it with some other useful elements of the VBA coding language, you can create powerful stuff (covered in the examples later in this tutorial).

What Does VBA Dir Function Do?

Use VBA DIR function when you want to get the name of the file or a folder, using their path name.

To give you an example, if you have an Excel file in a folder, you can use the VBA DIR function to get the name of that Excel file (or any other type of file).

What if I want to get the names of all the Excel files in the folder (or all the files – be it Excel file or not)?

You can do that too!

When you use DIR function once, it returns the first file name in a folder. Now if you want to get the names of the second, third, fourth files as well, you can use the DIR function again (covered later as an example).

Dir returns the first file name that matches the pathname. To get any additional file names that match pathname, call Dir again with no arguments. When no more file names match, Dir returns a zero-length string (“”). Covered in Example 3 and 4 later in this tutorial.

Syntax of VBA DIR Function

Dir [ (pathname [ ,attributes ] ) ]
  • pathname: This is an optional argument. This can be the file name, folder name, or directory name. If pathname is not found, VBA DIR function returns a zero-length string (“”)
  • attributes: This is an optional argument. You can use this argument to specify some attributes and DIR function will return the file names based on those attributes. For example, if you want a list of all hidden files or read-only files (along with files with no attributes), you need to specify that in this argument.

Attributes available to use in VBA DIR function (you can use one or more of these):

Constant Value Description
vbNormal 0 (Default) Specifies files with no attributes.
vbReadOnly 1 Specifies read-only files in addition to files with no attributes.
vbHidden 2 Specifies hidden files in addition to files with no attributes.
VbSystem 4 Specifies system files in addition to files with no attributes. Not available on the Macintosh.
vbVolume 8 Specifies volume label; if any other attributed is specified, vbVolume is ignored. Not available on the Macintosh.
vbDirectory 16 Specifies directories or folders in addition to files with no attributes.
vbAlias 64 Specified file name is an alias. Available only on the Macintosh.

Using Wildcard Characters with DIR Function

If you’re working with Windows, you can also use the wildcard characters in the DIR function.

Note that you can not use these when working with VBA in Macintosh.

Using wildcards can be useful when:

  • You want to get the file names of a particular file type (such as .XLSX or .PPTX)
  • When you have a specific suffix/prefix in filenames and you want to get the names of these files/folders/directories. For example, if you want the names of all the files with the prefix 2019 in it, you can do that using wildcard characters.

There are three wildcard characters in Excel:

  1. * (asterisk) – It represents any number of characters. For example, 2019* would give you the names of all the files with the prefix 2019 in it.
  2. ? (question mark) – It represents one single character. For example, 2019? would give you the names of all the files that start with 2019 and has one more character in the name (such as 2019A, 2019B, 2019C, and so on)

Note: There is one more wildcard character – tilde (~). Since it’s not used a lot, I have skipped its explanation. You can read more about it here if interested.

VBA DIR Function – Examples

Now let’s dive in and see some examples of using the VBA DIR function.

Example 1 – Getting the File Name from its Path

When you have the path of a file, you can use the DIR function to get the name of the file from it.

For example, the below code returns the name of the file and shows it in a message box.

Sub GetFileNames()
Dim FileName As String
FileName = Dir("C:UserssumitDesktopTestExcel File A.xlsx")
MsgBox FileName
End Sub

The above code uses a variable ‘FileName’ to store the file name that is returned by the DIR function. It then uses a message box to display the file name (as shown below).

File Name using VBA DIR Function

And what happens when the file doesn’t exist?

In that case, the DIR function would return an empty string.

The below code uses an If Then Else statement to check whether the file exists or not. If the file doesn’t exist, it shows a message box with a text “File Doesn’t Exist”, else it shows the file name.

Sub CheckFileExistence()
Dim FileName As String
FileName = Dir("C:UserssumitDesktopTestExcel File A.xlsx")

If FileName <> "" Then
    MsgBox FileName
Else
    MsgBox "File Doesn't Exist"
End If

End Sub

Example 2 – Check if a Directory Exists or Not (and create if it doesn’t)

The below code checks whether the folder ‘Test’ exists or not.

A message box is used to show a message in case the folder exists or when it doesn’t exist.

Sub CheckDirectory()
Dim PathName As String
Dim CheckDir As String

PathName = "C:UserssumitDesktopTest"
CheckDir = Dir(PathName, vbDirectory)

If CheckDir <> "" Then
    MsgBox CheckDir & " exists"
Else
    MsgBox "The directory doesn't exist"
End If

End Sub

You can refine this code further to check whether the folder exists or not, and if it doesn’t, then you can use VBA to create that folder.

Below is the code that uses the MkDir function to create a folder in case it doesn’t exist.

Sub CreateDirectory()
Dim PathName As String
Dim CheckDir As String

PathName = "C:UserssumitDesktopTest"
CheckDir = Dir(PathName, vbDirectory)

If CheckDir <> "" Then
    MsgBox CheckDir & " folder exists"
Else
    MkDir PathName
    MsgBox "A folder has been created with the name" & CheckDir
End If

End Sub

Example 3 – Get the Names of All File and Folders in a Directory

If you want to get a list of all the file and folder names in a directory, you can use the DIR Function.

The below code lists all the files and folder names in the Test folder (which is located at the following path – C:UserssumitDesktopTest).

I am using Debug.Print to show the names in the Immediate window. You can also use this to list the names in a message box or in a column in Excel.

Sub GetAllFile&FolderNames()
Dim FileName As String
FileName = Dir("C:UserssumitDesktopTest", vbDirectory)

Do While FileName <> ""
    Debug.Print FileName
    FileName = Dir()
Loop
End Sub

The Do While loop in the above code continues till all the files and folders in the given path have been covered. When there are no more files/folders to cover, FileName becomes a null string and the loop stops.

Example 4 – Get the Names of All Files in a Folder

You can use the below code to get the names of all the files in a folder/directory (and not the names of the sub-folders).

Sub GetAllFileNames()
Dim FileName As String
FileName = Dir("C:UserssumitDesktopTest")

Do While FileName <> ""
    Debug.Print FileName
    FileName = Dir()
Loop
End Sub

This code is just like the code used in Example 3, with one minor difference.

In this code, I have not specified vbDirectory in the DIR function. When you specify vbDirectory, it will give you the names of all the files as well as folders.

When you don’t specify vbDirectory, DIR function will only give you the names of the files.

Note: If you want to get the names of all the files in the main folder and the sub-folders, you can’t use the DIR function (as it’s not recursive). To do this, you can either use Power Query (no coding needed) or use the File System Object in VBA (with recursion).

Example 5 – Get the Names of All the Sub-Folders within a Folder

The below code would give you the names of all the sub-folders within the specified folder.

It uses the GetAtr function in VBA, which allows us to check whether the name returned by the DIR function is the name of a file or a folder/directory.

Sub GetSubFolderNames()
Dim FileName As String
Dim PathName As String

PathName = "C:UserssumitDesktopTest"
FileName = Dir(PathName, vbDirectory)

Do While FileName <> ""
If GetAttr(PathName & FileName) = vbDirectory Then
    Debug.Print FileName
End If
FileName = Dir()
Loop
End Sub

Again, I am using Debug.Print to get the names in the immediate window. You can get these in a message box or in Excel (by modifying the code accordingly).

Example 6 – Get the First Excel File from a Folder

With DIR function, you can specify the file extension or any suffix/prefix that you want in the file name that is returned.

The below code would display the name of the first Excel file in the Test folder.

Sub GetFirstExcelFileName()
Dim FileName As String
Dim PathName As String

PathName = "C:UserssumitDesktopTest"
FileName = Dir(PathName & "*.xls*")
MsgBox FileName
End Sub

Note that I have used *.xls* (asterisk sign on both sides). This will ensure that all the versions of Excel files are checked (.xls, xlsx, .xlsm, .xlsb).

Example 7 – Get Names of All Excel File in a Folder

Use the below code to get the names of all the Excel files in the Test folder.

Sub GetAllFileNames()
Dim FolderName As String
Dim FileName As String
FolderName = "C:UserssumitDesktopTest"
FileName = Dir(FolderName & "*.xls*")

Do While FileName <> ""
    Debug.Print FileName
    FileName = Dir()
Loop

End Sub

While the DIR function returns the name of the first Excel file only, since we are calling it again in the loop, it goes through all the files and gives us the names of all the Excel files.

Hope you found this tutorial and the examples useful.

Let me know your thoughts in the comments section.

You May Also Like the Following Excel Tutorials:

  • Excel VBA InStr Function.
  • Excel VBA Split Function.
  • Excel VBA TRIM Function
  • VBA LCASE Function.
  • VBA UCASE Function.

I have a macro-enabled WorkBook. I need to specify the current folder in which the macro-enabled file is present as the path. I tried setting

path = ActiveWorkbook.Path

and

path = CurDir()

but neither of these work for me. Any idea on this?

ashleedawg's user avatar

ashleedawg

20k8 gold badges73 silver badges104 bronze badges

asked Apr 18, 2012 at 18:27

user1270123's user avatar

9

If the path you want is the one to the workbook running the macro, and that workbook has been saved, then

ThisWorkbook.Path

is what you would use.

answered Apr 18, 2012 at 19:04

Tim Williams's user avatar

Tim WilliamsTim Williams

150k8 gold badges96 silver badges124 bronze badges

0

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "*.csv")

and

With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "" & strFile, _

answered Apr 18, 2012 at 20:14

Siddharth Rout's user avatar

Siddharth RoutSiddharth Rout

146k17 gold badges206 silver badges250 bronze badges

Mojakhed

0 / 0 / 0

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

Сообщений: 13

1

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

23.10.2012, 11:58. Показов 89707. Ответов 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



 

Jonych

Пользователь

Сообщений: 26
Регистрация: 13.01.2016

Приветствую.
Необходимо, чтобы в ячейку B3 (а так же во все остальные) подставлялся путь, который будет выводиться в ячейку A1.
Что-то типа: =(A1)[01.xlsm]Тек….
Видел варианты с VBA, но (если я правильно понял), везде надо выполнять команду. Имеется необходимость сделать это без каких-то дополнительных действий.
Функция «ЯЧЕЙКА» выводит путь с текущим именем листа. Просматривал все варианты, только VBA. Если есть возможность реализовать это через вба без дополнительных кликов, то так же прошу помочь с решением. Спасибо!

Изменено: Jonych13.01.2016 02:57:14
(Неверное отображение скриншота)

 

KL

Пользователь

Сообщений: 2186
Регистрация: 01.01.2013

Так?

Прикрепленные файлы

  • Book1.xlsx (9.16 КБ)

 

Андрей VG

Пользователь

Сообщений: 11878
Регистрация: 22.12.2012

Excel 2016, 365

Доброе время суток
Скорее требуется как в ячейке B10 на примере ячейки B7
Успехов.

 

Jonych

Пользователь

Сообщений: 26
Регистрация: 13.01.2016

Спасибо за решение.
=ЛЕВСИМВ(ЯЧЕЙКА(«filename»); НАЙТИ(«[«;ЯЧЕЙКА(«filename»))-1) — то, что необходимо. Однако проблема осталась нерешенная.
Сейчас пытаюсь реализовать: см. скриншот.

 

KL

Пользователь

Сообщений: 2186
Регистрация: 01.01.2013

 Как показано в файле от Андрей VG

=ДВССЫЛ(««&B5&»[01.xlsm]Текущий день!C23″)
будьте внимательны — не пропустите апострофы перед путем и перед восклицательным знаком.

 

KL

Пользователь

Сообщений: 2186
Регистрация: 01.01.2013

Можно еще так если хотите ссылаться на реальную ячейку в данном файле, чтобы динамически менять адрес:
=ДВССЫЛ(««&$B$5&»[01.xlsm]Текущий день!»&АДРЕС(СТРОКА(C23);СТОЛБЕЦ(C23)))

Изменено: KL01.03.2016 11:57:00

 

Jonych

Пользователь

Сообщений: 26
Регистрация: 13.01.2016

#7

14.01.2016 00:46:44

Цитата
KL написал: =ДВССЫЛ(«‘»&B5&»[01.xlsm]Текущий день’!C23»)

Хм. Только сейчас понял, что он выдает путь на …Desktop, хотя файл находится абсолютно в другой папке: C:UsersName1DropboxFolder
Функция:

Код
=ЛЕВСИМВ(ЯЧЕЙКА("filename"); НАЙТИ("[";ЯЧЕЙКА("filename"))-1)

выдает C:UsersName1Desktop

 

KL

Пользователь

Сообщений: 2186
Регистрация: 01.01.2013

Формула =ЯЧЕЙКА(«filename») выдает путь именно к тому файлу, в котором используется и не ошибается :)

 

Jonych

Пользователь

Сообщений: 26
Регистрация: 13.01.2016

Вроде всё проверил, что не так?
P.S. Путь определяется верно, я с файлами запутался немного)

 

KL

Пользователь

Сообщений: 2186
Регистрация: 01.01.2013

Все так, но ДВССЫЛ работает только с открытыми файлами

 

Jonych

Пользователь

Сообщений: 26
Регистрация: 13.01.2016

Вот тут то вся и беда). Так как файл, который подбирает инфу из других файлов находится в дропбоксе, то путь постоянно меняется. + по завершению месяца переносится в отдельную папку. Использую ctrl+h и замену пути. Получается, автоматизировать данный процесс не получится.
P.S. Можно было бы перейти на тот же one drive, однако папку дропбокс можно хранить в определенном каталоге на диске (поэтому на нескольких компах одинаковый путь), но не на всех)

Изменено: Jonych14.01.2016 02:01:34

 

KL

Пользователь

Сообщений: 2186
Регистрация: 01.01.2013

 

Jonych

Пользователь

Сообщений: 26
Регистрация: 13.01.2016

Примерно понял, что делают эти функции и как работает, но у меня больше тысячи ячеек :P. Писать скрипт по каждой — неверный метод)

 

KL

Пользователь

Сообщений: 2186
Регистрация: 01.01.2013

Ну тогда вариантов почти не остаётся. Если файл используется только вами и не предназначен для рассылки, то поинтересуйтесь надстройкой написанной Laurent Longre, в которой есть функция листа INDIRECT.EXT или надстройкой написанной Harlan Grove, где есть функция листа PULSE. Я их сам не пробовал, но когда-то рекомендовали как решение. Вполне возможно, что за давностью лет они и перестали работать в последних версиях Excel, но может имеет смысл попытать счастья. Удачи.

добавлено: фунция PULSE, похоже, использует ADO, так что наверняка медленная.

Изменено: KL15.01.2016 02:25:49

 

Jonych

Пользователь

Сообщений: 26
Регистрация: 13.01.2016

Ок. Спасибо вам большущее за помощь, буду пробовать :)

 

Jonych

Пользователь

Сообщений: 26
Регистрация: 13.01.2016

#16

15.01.2016 02:43:12

Хотя, у меня только что появилась идея, как реализовать через VBA.

Код
Sub Путь()
i = Application.ActiveWorkbook.Path
Range("B1") = i
End Sub

А так как путь у нас постоянный: =’C:DropboxFolder[03.xlsm]Текущий день’!$AJ$23, за исключением всего, что написано до символа «[«, то можно далее добавить замену символов до «[» на то, что получается в B1 во всех ячейках. Реализуемо?
02:45 Получается, вся проблема в выборке всех символов до «[«. Можно даже вручную проставить несколько диапазонов, чтобы не накосячить случайно.
02:49 Если первый символ = [, Paste B1, else удалить, repeat. Что-то типа такого.
03:47 Если вставлять путь через инпут бокс, то он отображается как ссылка именно. Полагаю, что замена символов до «[» решит проблему. Пора спать…)

Изменено: Jonych15.01.2016 03:48:45

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#17

15.01.2016 09:57:01

Цитата
KL написал:
=ЯЧЕЙКА(«filename») выдает путь именно к тому файлу, в котором используется и не ошибается

Кирилл, что-то меня терзают смутные сомнения…Если не указать второй аргумент(адрес ячейки), то функция вернет путь до активного на момент пересчета файла, а не путь до файла с функцией. Т.е. корректней будет так:
ЯЧЕЙКА(«filename»;A1)

Jonych, я так до конца и не понял, что Вам надо. Возможно, какой-нибудь вариант на макросах из моей статьи подойдет:

Как получить данные из закрытой книги?

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

KL

Пользователь

Сообщений: 2186
Регистрация: 01.01.2013

The_Prist, согласен :)

 

Jonych

Пользователь

Сообщений: 26
Регистрация: 13.01.2016

Если все-таки решу вопрос, то отпишусь) спасибо за помощь!)

 

Jonych

Пользователь

Сообщений: 26
Регистрация: 13.01.2016

Все-таки не получилось). Перейти на one-drive с динамическими путями (в зависимости от пользователя компа) не получится. Остается Dropbox со стационарным путем C:DropboxПапкафайлы.xlsx

 

Jonych

Пользователь

Сообщений: 26
Регистрация: 13.01.2016

Накопал идею:

http://forum.msexcel.ru/index.php?topic=1920.0

. Там много всего, но смысл в том, чтобы сделать кнопку «обновить данные», и по нажатию в невидимом режиме открывается 31 файл, данные обновляются, файлы закрываются.  

 

Hugo

Пользователь

Сообщений: 23251
Регистрация: 22.12.2012

#22

02.02.2016 15:00:58

Цитата
Jonych написал:
смысл в том, чтобы сделать кнопку «обновить данные»

и как же тогда «Реализация без VBA»?

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Jonych

Пользователь

Сообщений: 26
Регистрация: 13.01.2016

#24

02.02.2016 17:02:25

Цитата
Hugo написал: и как же тогда «Реализация без VBA»?

Если других вариантов нет, пробуем такой)

 

Jonych

Пользователь

Сообщений: 26
Регистрация: 13.01.2016

#25

01.03.2016 01:03:30

Заказал за 300р на фрилансе скрипт. Прикладываю ниже:

Код
Sub Обновить_пути()
  thisdir = ThisWorkbook.Path ' расположение текущего файла
  Application.DisplayAlerts = False
  Set c = Cells.Find("Dropbox", LookIn:=xlFormulas)
  If Not c Is Nothing Then
     firstAddress = c.Address
     Do
        dirr = Cells(c.Row, c.Column).Formula
        If InStr(dirr, "xls") <> 0 Then
           dirr = Split(dirr, "")
           dirr2 = ""
           For Each d In dirr
               If InStr(d, "xls") = 0 Then
                  dirr2 = dirr2 & d & ""
               End If
           Next
           dirr2 = Replace(dirr2, "='", "")
           f = CStr(Cells(c.Row, c.Column).Formula)
           f2 = Replace(f, dirr2, thisdir & "")
           Cells(c.Row, c.Column).Formula = f2
        End If
        Set c = Cells.FindNext(c)
        If c Is Nothing Then
           Exit Do
        End If
        Loop While Not c Is Nothing And c.Address <> firstAddress
    End If
    Application.DisplayAlerts = True
End Sub
 

vaspup88

Пользователь

Сообщений: 54
Регистрация: 19.04.2019

#26

21.09.2019 15:26:34

Здравствуйте! Помогите, я знаю. вам это будет легко :)
имеется макрос

Код
Sub Выбор_файла()
    Filename$ = GetFilePath()
    If Filename$ = "" Then Exit Sub
    MsgBox "Выбран файл: " & Filename$
End Sub
 
Function GetFilePath(Optional ByVal Title As String = "Выбрать файл", _
                     Optional ByVal InitialPath As String = "c:", _
                     Optional ByVal FilterDescription As String = "Файл Excel", _
                     Optional ByVal FilterExtention As String = "*.xls*") As String
    On Error Resume Next
    With Application.FileDialog(msoFileDialogOpen)
        .ButtonName = "Выбрать": .Title = Title:
        .InitialFileName = GetSetting(Application.Name, "GetFilePath", "folder", InitialPath)
        .Filters.Clear: .Filters.Add FilterDescription, FilterExtention
        If .Show <> -1 Then Exit Function
        GetFilePath = .SelectedItems(1)
        folder$ = Left(.SelectedItems(1), InStrRev(.SelectedItems(1), ""))
        SaveSetting Application.Name, "GetFilePath", "folder", folder$
    End With
   End Function

как вывести пусть файла в определенную ячейку?

Изменено: vaspup8821.09.2019 16:07:05

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

vaspup88, код следует оформлять соответствующим тегом: ищите такую кнопку (см. скрин) и исправьте своё сообщение.

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#28

21.09.2019 15:51:07

Код
Sub Выбор_файла()
   Filename$ = GetFilePath()
   If Filename$ = "" Then Exit Sub
   MsgBox "Выбран файл: " & Filename$
   Range("A1") = Filename$ 'Добавлено
End Sub
 

vaspup88

Пользователь

Сообщений: 54
Регистрация: 19.04.2019

#29

21.09.2019 16:07:50

Цитата
Юрий М написал:
код следует оформлять соответствующим тегом: ищите такую кнопку (см. скрин) и исправьте своё сообщение.

сделал :) извиняюсь…спасибо огромное!

Изменено: vaspup8821.09.2019 16:08:14

 

vaspup88

Пользователь

Сообщений: 54
Регистрация: 19.04.2019

#30

21.09.2019 18:59:52

а как сократить весь путь до имени файла с расширением? причем с выводом в определенную ячейку :)

Изменено: vaspup8821.09.2019 20:29:43

Содержание

  1. Объект FileSystemObject
  2. Синтаксис
  3. Примечания
  4. Методы
  5. Свойства
  6. См. также
  7. Поддержка и обратная связь
  8. Функция Dir
  9. Синтаксис
  10. Параметры
  11. Примечания
  12. См. также
  13. Поддержка и обратная связь
  14. Daily Dose of Excel
  15. Haphazardly Posted Excel Information and Other Stuff
  16. Get the Path to My Documents in VBA
  17. 23 thoughts on “ Get the Path to My Documents in VBA ”

Объект FileSystemObject

Предоставляет доступ к файловой системе компьютера.

Синтаксис

Scripting.FileSystemObject

Примечания

Приведенный ниже код иллюстрирует использование объекта FileSystemObject для возврата объекта TextStream, который можно читать, и в который можно записать данные.

  • Функция CreateObject возвращает объект FileSystemObject ( fs ).
  • Метод CreateTextFile создает файл в качестве объекта TextStream ( a ).
  • Метод WriteLine записывает строку текста в созданный текстовый файл.
  • Метод Close опустошает буфер и закрывает файл.

Методы

Метод Описание
BuildPath Добавляет имя в существующий путь.
CopyFile Копирует один или несколько файлов из одного расположения в другое.
CopyFolder Копирует одну или несколько папок из одного расположения в другое.
CreateFolder Создает новую папку.
CreateTextFile Создает текстовый файл и возвращает объект TextStream, который можно использовать для чтения или записи в файл.
DeleteFile Удаляет один или несколько указанных файлов.
DeleteFolder Удаляет одну или несколько указанных папок.
DriveExists Проверяет, существует ли указанный диск.
FileExists Проверяет, существует ли указанный файл.
FolderExists Проверяет, существует ли указанная папка.
GetAbsolutePathName Возвращает полный путь из корневого каталога диска для указанного пути.
GetBaseName Возвращает базовое имя указанного файла или папки.
GetDrive Возвращает объект Drive, соответствующий диску в указанном пути.
GetDriveName Возвращает имя диска указанного пути.
GetExtensionName Возвращает имя расширения файла для последнего компонента в указанном пути.
GetFile Возвращает объект файла для указанного пути.
GetFileName Возвращает имя файла или папки для последнего компонента в указанном пути.
GetFolder Возвращает объект Folder для указанного пути.
GetParentFolderName Возвращает имя родительской папки последнего компонента в указанном пути.
GetSpecialFolder Возвращает путь к некоторым специальным папкам Windows.
GetTempName Возвращает созданный случайным образом временный файл или папку.
Move Перемещает заданный файл или указанную папку из одного места в другое.
MoveFile Перемещает один или несколько файлов из одного места в другое.
MoveFolder Перемещает одну или несколько папок из одного места в другое.
OpenAsTextStream Открывает указанный файл и возвращает объект TextStream, который можно использовать для считывания, записи и дополнения данных в файле.
OpenTextFile Открывает файл и возвращает объект TextStream, который можно использовать для доступа к файлу.
WriteLine Записывает заданную строку и символ новой строки в файл TextStream.

Свойства

Свойство Описание
Drives Возвращает коллекцию всех объектов Drive на компьютере.
Name Устанавливает или возвращает имя указанного файла или заданной папки.
Path Возвращает путь для указанного файла, диска или указанной папки.
Size Для файлов возвращает размер указанного файла в байтах; для папок возвращает размер всех файлов и вложенных папок в байтах.
Type Возвращает сведения о типе файла или папки (например, для файлов с расширением .TXT возвращается «Text Document»).

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Функция Dir

Возвращает значение типа String, определяющее имя файла, каталога или папки, которое соответствует указанному шаблону, атрибуту файла либо метке тома диска.

Синтаксис

Dir [ (pathname, [ attributes ] ) ]

Синтаксис функции Dir состоит из следующих элементов.

Часть Описание
pathname Необязательный. Строковое выражение, указывающее имя файла; может включать каталог или папку, а также диск. Если файл, указанный параметром pathname, не найден, возвращается строка нулевой длины («»).
attributes Необязательный. Константа или числовое выражение, определяющее атрибуты файла. Если этот параметр опущен, возвращаются файлы, которые соответствуют параметру pathname, но не имеют атрибутов.

Параметры

Константа Значение Описание
vbNormal 0 (По умолчанию.) Определяет файлы без атрибутов.
vbReadOnly 1 В дополнение к файлам без атрибутов определяет файлы, доступные только для чтения.
vbHidden 2 Определяет скрытые файлы, а также файлы без атрибутов.
vbSystem 4 В дополнение к файлам без атрибутов определяет системные файлы. Недоступно в macOS.
vbVolume 8 Определяет метку тома; если указан какой-либо другой атрибут, параметр vbVolume игнорируется. Недоступно в macOS.
vbDirectory 16 В дополнение к файлам без атрибутов определяет каталоги (папки).
vbAlias 64 Указанное имя файла является псевдонимом. Доступно только в macOS.

Эти константы определены в Visual Basic для приложений и могут использоваться в коде вместо фактических значений.

Примечания

В Microsoft Windows и macOS Dir поддерживает использование подстановочных знаков с несколькими символами (*) и одним символом (?) для указания нескольких файлов.

Так как macOS не поддерживает использование подстановочных знаков, для определения группы файлов используйте тип файла. Чтобы вместо имен файлов указать тип файла, воспользуйтесь функцией MacID. Например, следующий оператор возвращает имя первого текстового файла в текущей папке:

Чтобы вывести следующий файл в папке, укажите пустую строку:

Если функция MacID используется с функцией Dir в Microsoft Windows, возникает ошибка.

Любое значение атрибута, превышающее 256, считается значением MacID.

Значение pathname необходимо указать при первом вызове функции Dir, иначе произойдет ошибка. Если задаются атрибуты файла, значение pathname также должно быть указано.

Функция Dir возвращает первое имя файла, соответствующее значению pathname. Для получения дополнительных имен файлов, соответствующих значению pathname, вызовите функцию Dir повторно без аргументов. Если других соответствий найдено не будет, функция Dir возвратит пустую строку («»). После возврата строки нулевой длины в последующих вызовах необходимо указывать значение pathname, иначе произойдет ошибка.

Значение pathname можно изменить без получения всех имен файлов, соответствующих текущему значению pathname. Однако нельзя осуществить рекурсивный вызов функции Dir. С помощью функции Dir с атрибутом vbDirectory невозможно последовательно возвращать подкаталоги.

Так как имена файлов возвращаются в порядке без учета регистра для Windows и с учетом регистра для macOS, их можно сохранить в массиве и затем отсортировать массив.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Daily Dose of Excel

Haphazardly Posted Excel Information and Other Stuff

Get the Path to My Documents in VBA

VBA has an Environ function. To get a list of all the Environ variables you can see, you can use the method at VBA Express. I use the USERPROFILE argument like this

You can also use the Windows API as described at My Documents + Environment Variables

23 thoughts on “ Get the Path to My Documents in VBA ”

One can also look up Excel VBA help for ‘environ’ (w/o the quotes) and get pretty exhaustive information including what I suspect is the “base” code for most examples one finds on various websites.

Your code gives an incorrect answer on my system. It returns “C:Documents and SettingsusernameMy Documents”, but that folder doesn’t exist on this computer. I have the “My Documents” folder on a different drive than the username folder. In fact, I don’t have a folder called “My Documents” anywhere. But, I can click on the “My Documents” folder that is on my desktop and it will show me the same files as if I navigated directly to “D:username”.

I did a quick search for an environment variable that would expose where this desktop folder actually points to, but I came up empty-handed.

Environ is okay for some directory lookups, but to get them all, reliably, you need to use Windows APIs:

Private Declare Function SHGetFolderPath Lib “shfolder.dll” _
Alias “SHGetFolderPathA” _
( ByVal hwndOwner As Long , _
ByVal nFolder As Long , _
ByVal hToken As Long , _
ByVal dwReserved As Long , _
ByVal lpszPath As String ) As Long

Function MyDocumentsDir()
Dim sBuffer As String
sBuffer = Space$(260)
If SHGetFolderPath(&H0, &H5, -1, &H0, sBuffer) = 0 Then
MyDocumentsDir = Left$(sBuffer, lstrlenW(StrPtr(sBuffer)))
End If
End Function

Another way using Wscript:

MsgBox objFolders( “desktop” )
MsgBox objFolders( “allusersdesktop” )
MsgBox objFolders( “sendto” )
MsgBox objFolders( “startmenu” )
MsgBox objFolders( “recent” )
MsgBox objFolders( “favorites” )
MsgBox objFolders( “mydocuments” )
End Function

I had the environ function in my notes for a rainy day, can’t remember why I Googled it in the first place. being in application support where I get to tinker with all sorts of software I’m always interested in finding the ‘joins’ between them. Usually knowing the strengths and capabilities of different scripting languages and software, plus where they can be joined to feed one into the next, gives me the sort of quick and dirty answers I need.

But Dick specifies it as Environ$, why the $? is it purely optional or does it have a modifying effect?

It’s a habit I developed based on that article.

Mike, your code using Wscript correctly identified where the “My Documents” folder on my desktop actually resides on my computer. I’m sure you knew it would! Thank you for that.

I’ve done a couple minor one-off type spreadsheets that relied on nobody doing what I did to my home computer. That’s not optimal and was bound to backfire on me some day. Now I can fix the code.

The other part I like about it is that I can actually read and follow the code. I know I could incorporate that into my projects without wondering why it worked.

Omar:
“I can actually read and follow the code..I know I could incorporate that into my projects without wondering why it worked.”

You know…it’s funny you say that. I recently spent some time gathering some code examples for a class I’m giving and I realized that I often lean toward variations of code that I can read and understand. I’m sure that leaves me doing some things “inefficiently”. But I’m willing to trade some inefficiency for something I can read and explain to others.

I remember Bill Jelen once told me that Aladin Akyurek (a poster on his site) creates the most amazing array formulas to solve most problems. He tells people that if they ever get a formula from Aladin, just copy and paste it into the cell. Don’t worry how it works…it will just work. I can, of course, appreciate the charm of that statement, but I know it would frustrate me on some level to have some formula I don’t fully understand working in my spreadsheet.

I guess I feel the same way about code.

Mike, my lesson is some code (found on the internet from a trustworthy source) that I’m using to add and remove file folders. This particular code won’t remove a folder with a hidden or system file in it. Which means most folders that have had a picture in it that has been viewed using Thumbnails. Since the purpose of these folders is to contain pictures, well you get the idea. I end up copying the list of folders that need removing to a DOS batch file and delete them that way.

Since I don’t understand the code, I don’t know how to modify it, or whether it is even possible to modify it.

I had no idea you could access Wscript from VBA. I will be looking into that possibility to do this task.

I agree with Jon the only reliable way to get the system folders is with the API. Environ can certainly fail (as in not return an expected result) in some systems and WScript might be disabled (it’s also slow while the object is created).

For readability use the conventionally named constants, eg
Const CSIDL_PERSONAL = &H5 ‘ my documents
(ignore any “amp;” that might creep in before the “H”)

Thanks to Mike (Alexander) .. in the environment I’m working in we have roaming profiles and the my documents folder is set to a network folder, yours was the only method that actually picked up the right address so thanks a lot for posting it!

[…] Forums http://www.thecodecage.com/forumz/excel-vba-programming/160189-file-path.html#post579392 Daily Dose of Excel » Blog Archive » Get the Path to My Documents in VBA and here Locating Home My Documents Folder – Excel Help & Excel Macro Help […]

To be sure, the code should probably look like the following (it’s missing an extra “\” &

Источник

Понравилась статья? Поделить с друзьями:
  • Vba excel userform resize
  • Vba excel with events
  • Vba excel workbooks methods
  • Vba excel адрес текущей ячейки
  • Vba excel userform queryclose