Vba excel директория файла

I am using MS Excel 2010 and trying to get the current directory using the below code,

    path = ActiveWorkbook.Path

But ActiveWorkbook.Path returns blank.

Jean-François Corbett's user avatar

asked Nov 6, 2013 at 22:26

Ullan's user avatar

1

When one opens an Excel document D:dbtmptest1.xlsm:

  • CurDir() returns C:Users[username]Documents

  • ActiveWorkbook.Path returns D:dbtmp

So CurDir() has a system default and can be changed.

ActiveWorkbook.Path does not change for the same saved Workbook.

For example, CurDir() changes when you do «File/Save As» command, and select a random directory in the File/Directory selection dialog. Then click on Cancel to skip saving. But CurDir() has already changed to the last selected directory.


[ADD]
Resume VBA for different applications

Access D:dbtmptest1.accdb, like duckboy81 commented:

  1. CurDir() => C:Users[username]Documents
  2. Application.CurrentProject.Path => D:dbtmp

Excel D:dbtmptest1.xlsm:

  1. CurDir() => C:Users[username]Documents
  2. ActiveWorkbook.Path => D:dbtmp
  3. Application.DefaultFilePath => C:Users[username]Documents

Outlook:

  1. CurDir() => C:WINDOWSSystem32
  2. Application.Session.Stores(1).Filepath => D:programdataOutlookmyOutlookDocX.pst

PowerPoint D:dbtmptest1.ppt:

  1. CurDir() => C:Users[username]Documents
  2. ActivePresentation.Path => D:dbtmp

Word D:dbtmptest1.docx:

  1. CurDir() => C:Users[username]Documents
  2. Application.ActiveDocument.Path => D:dbtmp
  3. Application.ActiveDocument.FullName => D:dbtmptest1.docx
  4. Application.StartupPath => C:users[username]appdataroamingmicrosoftwordstartup

answered Nov 6, 2013 at 22:47

jacouh's user avatar

jacouhjacouh

8,3275 gold badges30 silver badges43 bronze badges

3

You have several options depending on what you’re looking for.
Workbook.Path returns the path of a saved workbook. Application.Path returns the path to the Excel executable. CurDir returns the current working path, this probably defaults to your My Documents folder or similar.

You can also use the windows scripting shell object’s .CurrentDirectory property.

Set wshell = CreateObject("WScript.Shell")
Debug.Print wshell.CurrentDirectory

But that should get the same result as just

Debug.Print CurDir

answered Nov 6, 2013 at 22:35

AndASM's user avatar

AndASMAndASM

9,0961 gold badge20 silver badges33 bronze badges

It would seem likely that the ActiveWorkbook has not been saved…

Try CurDir() instead.

answered Nov 6, 2013 at 22:35

Monty Wild's user avatar

Monty WildMonty Wild

3,9311 gold badge21 silver badges35 bronze badges

1

Your code: path = ActiveWorkbook.Path

returns blank because you haven’t saved your workbook yet.

To overcome your problem, go back to the Excel sheet, save your sheet, and run your code again.

This time it will not show blank, but will show you the path where it is located (current folder)

I hope that helped.

answered Jun 12, 2016 at 15:09

Mohamed Tahir's user avatar

Use Application.ActiveWorkbook.Path for just the path itself (without the workbook name) or Application.ActiveWorkbook.FullName for the path with the workbook name.

answered Nov 9, 2015 at 8:06

Agus Sapurta Sijabat's user avatar

This is the VBA that I use to open the current path in an Explorer window:

Shell Environ("windir") & "explorer.exe """ & CurDir() & "",vbNormalFocus

Microsoft Documentation:

  • CurDir Function
  • Environ Function
  • Shell Function

answered Nov 18, 2018 at 7:55

ashleedawg's user avatar

ashleedawgashleedawg

20k8 gold badges73 silver badges104 bronze badges

If you really mean pure working Directory, this should suit for you.

Solution A:

Dim ParentPath As String: ParentPath = ""
Dim ThisWorkbookPath As String
Dim ThisWorkbookPathParts, Part As Variant
Dim Count, Parts As Long

ThisWorkbookPath = ThisWorkbook.Path
ThisWorkbookPathParts = Split(ThisWorkbookPath, _
                        Application.PathSeparator)

Parts = UBound(ThisWorkbookPathParts)
Count = 0
For Each Part In ThisWorkbookPathParts
    If Count > 0 Then
        ParentPath = ParentPath & Part & ""
    End If
    Count = Count + 1
    If Count = Parts Then Exit For
Next

MsgBox "File-Drive = " & ThisWorkbookPathParts _
       (LBound(ThisWorkbookPathParts))
MsgBox "Parent-Path = " & ParentPath

But if don’t, this should be enough.

Solution B:

Dim ThisWorkbookPath As String

ThisWorkbookPath = ThisWorkbook.Path
MsgBox "Working-Directory = " & ThisWorkbookPath 

answered Nov 27, 2018 at 4:45

NOTSermsak's user avatar

NOTSermsakNOTSermsak

3561 gold badge8 silver badges8 bronze badges

Simple Example below:

Sub openPath()
Dim path As String
path = Application.ActivePresentation.path
Shell Environ("windir") & "explorer.exe """ & path & "", vbNormalFocus
End Sub

Amit Verma's user avatar

Amit Verma

8,5408 gold badges34 silver badges40 bronze badges

answered Feb 9, 2021 at 10:46

mariuszm's user avatar

1

Use these codes and enjoy it.

Public Function GetDirectoryName(ByVal source As String) As String()
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection

Dim source_file() As String
Dim i As Integer        

queue.Add fso.GetFolder(source) 'obviously replace

Do While queue.Count > 0
    Set oFolder = queue(1)
    queue.Remove 1 'dequeue
    '...insert any folder processing code here...
    For Each oSubfolder In oFolder.SubFolders
        queue.Add oSubfolder 'enqueue
    Next oSubfolder
    For Each oFile In oFolder.Files
        '...insert any file processing code here...
        'Debug.Print oFile
        i = i + 1
        ReDim Preserve source_file(i)
        source_file(i) = oFile
    Next oFile
Loop
GetDirectoryName = source_file
End Function

And here you can call function:

Sub test()
Dim s
For Each s In GetDirectoryName("C:New folder")
Debug.Print s
Next
End Sub

answered Dec 1, 2014 at 8:44

josef's user avatar

josefjosef

8449 silver badges8 bronze badges

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.

Get current working directory using VBA in Excel explained with examples. We use CurDir VBA function to find current working directory or folder. It displays system default directory. It can be changed using ChDir function.

Table of Contents:

  • Objective
  • Macro to find current working directory using VBA CurDir Function
  • Case study on Get current working directory
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

Macro to find current working directory using Excel VBA

Here we see the VBA macro to get current working directory using VBA in Excel. In this example we are using ‘CurDir’ VBA function to find the working directory.

'Find Get current working directory using VBA
Sub Find_Get_current_working_directory_using_VBA()

    'Variable declaration
    Dim sDir As String
   
    'Get current directory
    sDir = CurDir
    
    'Display output on the screen
    MsgBox "Current Directory is " & sDir
 
End Sub

Here is the output screenshot for your reference.

Get current working directory

Get current working directory

Case study on Get current working directory

Let us see another example to Get current working directory in Excel VBA.

Please find the following two statements.
The first one is

 
'Get Active Workbook Path
sWBPath = ActiveWorkbook.Path

Output: Active Workbook path is C:SomeswariVBAF1

The second one is

 
'Get current directory
sDir = CurDir

Output: Current Directory is C:VBAF1

If you want to change current directory from C:VBAF1 to C:SomeswariVBAF1, you can use ChDir VBA function in the following way.

i.e ChDir ActiveWorkbook.Path
or
ChDir C:SomeswariVBAF1

Now the below mentioned two statements displays same output.
Statement 1: sWBPath = ActiveWorkbook.Path
Statement 2: sDir = CurDir

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 VBA Text Files VBA Tables

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

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

 

KonstantinK

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

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

#1

28.01.2019 10:16:12

Доброго времени суток!

Мне нужно файл .xltm при вызове диалогового окна «Сохранить как» сохранить в текущей папке.Сразу скажу, что те ответы и примеры, которые есть на форуме мне не подходят. Также те примеры, что находил в сети тоже мимо. Дело в том, что есть много разных вариантов vba текстов вполне рабочих, но все они ориентированы на обычные excel файлы, а моём случае это файл шаблона с поддержкой макросов. Что я ни пробовал, всё равно для сохранения открывается системная папка «Документы». Есть подозрение,  что нужно искать обходной манёвр.

Код
Sub FileSaveAs(control As IRibbonControl)
Dim FileName As String
Dim CellValue As String
Dim xlfFileFormat As XlFileFormat: xlfFileFormat = xlOpenXMLWorkbookMacroEnabled
Dim Puth As String

'Вызов диалогового окна "Сохранить как" с заполнением имени файла
CellValue = ActiveWorkbook.Worksheets("Данные").Cells(3, 3)
FileName = "Безнал_Счёт " & CellValue

Puth = ""
Application.Dialogs(xlDialogSaveAs).Show FileName, xlfFileFormat, Puth
End Sub

Кнопка —>»Рабочая вкладка»  —> «Сохранить как»

Спасибо.

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

  • Тест.xltm (293.66 КБ)

Кто хочет — ищет способы, кто не хочет — причины (Сократ)

 

RAN

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

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

#2

28.01.2019 10:38:55

Цитата
KonstantinK написал: но все они ориентированы на обычные excel файлы

к коим относится и файл xltm.

 

не относится, т.к. один и тот же код в фале .xlm сохраняет в текущюю директорию, а в моём случае (.xltm — шаблон с поддержкой макросов) открывается папка «Документы» — ВСЕГДА!!!
Я это пишу, по-тому что пробовал не один код и всё время результат один и тот же.

Кто хочет — ищет способы, кто не хочет — причины (Сократ)

 

БМВ

Модератор

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

Excel 2013, 2016

Puth все ж Path, но не суть, У меня код пытается записать в текущую папку.

По вопросам из тем форума, личку не читаю.

 

KonstantinK

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

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

#5

28.01.2019 18:33:33

Я пробовал на разных компьютерах и в разных папках. Результат тот же — системная «Документы»
Загрузил код что бы проверить как видит Excel:

Код
Sub KKK()
Dim iPath As String
iPath = ThisWorkbook.Path
   MsgBox (iPath)
End Sub

Тоже — системная папка «Документы»
Указал точный адрес: в место Puth = «» записал iPuth = «C:UsersKonstantinDesktop123» — результат старый.
Уважаемый БМВ Вы скорее всего скопировали код и вставили в свой файл. Так не пойдёт. Фай именно шаблона .xltm

Изменено: KonstantinK28.01.2019 23:15:37

Кто хочет — ищет способы, кто не хочет — причины (Сократ)

 

Anchoret

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

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

Anchoret

#6

28.01.2019 18:33:44

Макрос где живет? В том файле, который сохраняете? Нужна его-же папка? Если да на все вопросы,то:

Код
fnp = ThisWorkbook.FullName
'или так уже без расширения файла
fnp = Split(ThisWorkbook.FullName, ".")(0)
'если только путь нужен, то
fnp = Replace(ThisWorkbook.FullName, ThisWorkbook.Name, "")

Изменено: Anchoret28.01.2019 18:36:50

 

KonstantinK

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

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

#7

28.01.2019 18:44:40

Проверил все варианты результат —> системная папка Документы

Цитата
Anchoret написал: Макрос где живет? В том файле, который сохраняете?

Макрос живёт в файле шаблона .xltm (исходный файл)
Сохраняется шаблон со всеми внутренностями в файл с расширением .xlsm (файл Excel с поддержкой макросов)

Кто хочет — ищет способы, кто не хочет — причины (Сократ)

 

Дмитрий(The_Prist) Щербаков

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

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

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

#8

28.01.2019 19:03:30

Цитата
KonstantinK написал:
сохранить в текущей папке

для начала надо понять что есть текущая папка. Вы вот что под этим подразумеваете? Это какая папка вообще? Вдруг это и есть всегда Документы? Поясните какая папка по Вашему текущая — тогда можно что-то придумать. Иначе — нет.
Я примерно покажу в чем суть. Для начала надо установить текущим диск, а потом папку на этом диске:

Код
ChDrive Left(ActiveWorkbook.Path, 1) 'назначаем текущим диск, в котором активная книга
ChDir ActiveWorkbook.Path 'назначаем текущей папку, в которой активная книга
Puth = ""
Application.Dialogs(xlDialogSaveAs).Show FileName, xlfFileFormat, Puth

это пример для активной книги. А уж какая директория нужна Вам — смотрите сами(то ли папка с шаблоном, то ли папка с чем-то еще….)

Изменено: Дмитрий(The_Prist) Щербаков28.01.2019 19:07:22

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

 

KonstantinK

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

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

#9

28.01.2019 19:10:42

Да это любая папка.
И вот что интересно макрос:

Код
Sub KKK()
Dim iPath As String
iPath = Application.PathSeparator
   MsgBox (iPath)
End Sub

при выполнении его командой макрос-выполнить показывает конечный каталог —> «»
но если совместить  код iPath = Application.PathSeparator с Application.Dialogs(xlDialogSaveAs).Show FileName, xlfFileFormat, iPuth
то опять предлагается системная папка Документы.  

Кто хочет — ищет способы, кто не хочет — причины (Сократ)

 

Дмитрий(The_Prist) Щербаков

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

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

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

#10

28.01.2019 19:12:20

Цитата
KonstantinK написал:
Да это любая папка

ну вот и как помогать? Чем тогда Документы не подходит? :) Она ведь тоже «любая» :)
Выше см. как можно сделать, чтобы в диалоге показывалась конкретная папка, как начальная. Других идей в качестве угадайки Ваших хотелок нет…

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

 

KonstantinK

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

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

#11

28.01.2019 19:27:22

Цитата
Дмитрий(The_Prist) Щербаков написал:
Чем тогда Документы не подходит?

Потому что Документы — это системная папка. Сам файл хранится у меня в одном месте у другого человека в своём месте. Каму где удобно. Но только не в системной «Документы»

Цитата
Дмитрий(The_Prist) Щербаков написал:
Выше см. как можно сделать, чтобы в диалоге показывалась конкретная папка, как начальная.

Выше вариантов НЕТ что бы конструкция Application.Dialogs(xlDialogSaveAs).Show (вызов диалогового окна «Сохранить как») решала мою проблему.
Мне вообще кажется, что решать через аргументы xlDialogSaveAs в шаблоне не получится.  

Кто хочет — ищет способы, кто не хочет — причины (Сократ)

 

Текущая папка для файла-шаблона всегда будет «Мои документы». А вот папку, куда нужно сохранить ваш файл *.xlsm нужно будет указать через диалоговое окно выбора папки.

 

Дмитрий(The_Prist) Щербаков

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

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

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

#13

28.01.2019 19:38:15

Цитата
KonstantinK написал:
Выше вариантов НЕТ

правда? А у меня работает предложенная мной конструкция(ChDrive и ChDir). При этом в любых пк и для любых диалоговых окон. единственное, что необходимо — знать конкретную папку и указать её коду. И пока Вы не определитесь какая нужна Вам(то ли папка с активной книгой, то ли папка с шаблоном, то ли еще какая) — код тем более не поймет. Он мысли читать не умеет, ему все показывать надо, а не заставлять додумывать.

Цитата
KonstantinK написал:
решать через аргументы xlDialogSaveAs в шаблоне не получится

в большинстве случаев да. Но выше я показал НЕ ЧЕРЕЗ аргументы. Вы хоть пробовали?

Изменено: Дмитрий(The_Prist) Щербаков28.01.2019 19:42:09

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

 

БМВ

Модератор

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

Excel 2013, 2016

#14

28.01.2019 19:43:07

Цитата
Михаил Витальевич С. написал:
Текущая папка для файла-шаблона всегда будет «Мои документы».

по тому что при открытии шаблона, путь отсутствует. Сделано это чтоб шаблон не переписали случайно. А при отсутствии пути путь для документов — это %USERPROFILE%Documents. И это право пользователя выбрать нужную папку.

По вопросам из тем форума, личку не читаю.

 

KonstantinK

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

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

#15

28.01.2019 20:23:00

Цитата
Дмитрий(The_Prist) Щербаков написал:
Вы хоть пробовали?

Да пробовал, вот результат: на ChDir ActiveWorkbook.Path ругается «path not found»
Дмитрий обратите внимание на интересный момент —>

Цитата
Дмитрий(The_Prist) Щербаков написал:
ChDrive Left(ActiveWorkbook.Path, 1) ‘назначаем текущим диск, в котором активная книгаChDir ActiveWorkbook.Path ‘назначаем текущей папку, в которой активная книгаPuth = «»Application.Dialogs(xlDialogSaveAs).Show FileName, xlfFileFormat, Puth

если я правильно понимаю то слова Puth в английском нет вообще — и мой косяк орфографическая ошибка и …
Странно, что ни кто не заметил раньше. Ведь если открыть сохранённый файл о попросит ввести пароль. С чего бы?

Кто хочет — ищет способы, кто не хочет — причины (Сократ)

 

БМВ

Модератор

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

Excel 2013, 2016

#16

28.01.2019 20:31:03

Цитата
KonstantinK написал: Странно, что ни кто не заметил раньше.

#4

Цитата
БМВ написал: Puth все ж Path, но не суть,

:-)

Изменено: БМВ28.01.2019 23:17:05

По вопросам из тем форума, личку не читаю.

 

Андрей VG

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

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

Excel 2016, 365

#17

28.01.2019 20:33:16

Цитата
KonstantinK написал:
на ChDir ActiveWorkbook.Path ругается «path not found»

Странно было бы, если бы не ругался. Активная книга только что создана по шаблону и ни разу не сохранялась.

Цитата
KonstantinK написал:
Сам файл хранится у меня в одном месте у другого человека в своём месте. Каму где удобно.

Как определить это своё место, каков критерий?
Если не устраивает Документы, то такой вариант

Код
Application.Dialogs(xlDialogSaveAs).Show Environ$("Temp")
 

Дмитрий(The_Prist) Щербаков

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

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

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

#18

28.01.2019 20:35:17

Цитата
KonstantinK написал:
ругается «path not found»

И Андрей уже рассказал почему.
Еще раз: пока Вы сами не определитесь какой путь для Вас «текущий» — ничего не получится.
Андрей, думаю лучше будет Environ(«userprofile») & «Desktop» — это хотя бы путь до рабочего стола.

Изменено: Дмитрий(The_Prist) Щербаков28.01.2019 20:37:30

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

 

Андрей VG

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

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

Excel 2016, 365

#19

28.01.2019 20:45:36

Цитата
Дмитрий(The_Prist) Щербаков написал:
лучше будет

Добрый вечер, Дмитрий. Полагаю, что лучше будет, чтобы пользователь, как честный человек, указал бы в настройках «Расположение локальных файлов по умолчанию» для того самого своего места. Тогда без проблем его можно было бы получить через Application.DefaultFilePath. Но все считают, что век искусственного интеллекта уже наступил, и что то самое своё место, это там, куда пользователь чаще всего что-то сохраняет. Чтобы Excel сам определял такое место, ну, или, как это сделано в других программах, указывал бы место последнего сохранённого файла :)

Изменено: Андрей VG28.01.2019 20:48:23

 

БМВ

Модератор

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

Excel 2013, 2016

#20

28.01.2019 20:48:23

Цитата
Дмитрий(The_Prist) Щербаков написал:
И Андрей уже рассказал почему.

Вот щас обидно! :-)  Я тут и про Puth и про путь

Цитата
БМВ написал:
по тому что при открытии шаблона, путь отсутствует. Сделано это чтоб шаблон не переписали случайно.

А Андрей рассказал :-)

KonstantinK, Единственный вариант, который поможет понять откель загружен шаблон, это хранить путь к шаблону, где либо, например в  

тут

А вот как путь будет туда попадать — это уже другая история.

По вопросам из тем форума, личку не читаю.

 

Андрей VG

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

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

Excel 2016, 365

#21

28.01.2019 20:51:02

Offtop

Цитата
БМВ написал:
что при открытии шаблона

Кто бы его явно открывал? Его просто использовали для размножения клонированием :)

 

sokol92

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

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

Здравствуйте, коллеги! Сплошная экзотика в этой теме. :)  А чем плох стандартный метод Application.GetSaveAsFilename?

 

Дмитрий(The_Prist) Щербаков

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

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

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

#23

28.01.2019 20:55:29

Цитата
БМВ написал:
Вот щас обидно

Ну, про Path это не моё :) К тому же судя по первому коду Puth — это вообще переменная :) Поэтому я на это не сильно внимания обращал. А про путь к файлам — видел ранее, но взял последнее «сказание от Андрея» :) Да и вообще намеки на это идут с самого начала, но ТС никак не может этого понять почему-то…

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

 

Ігор Гончаренко

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

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

#24

28.01.2019 20:59:31

Цитата
KonstantinK написал:
«Сохранить как» сохранить в текущей папке

господа, а что автор вкладывает в понятие текущая папка, кто-нибудь знает куда он собрался сохранить свой шаблон?
(кроме того что мы знаем — в текущую папку
ах, да! еще известно «Мои документы» — не подходит на роль текущей папки)

Изменено: Ігор Гончаренко28.01.2019 21:02:43

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

БМВ

Модератор

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

Excel 2013, 2016

Ігор Гончаренко, ну я так понимаю, что имелась в виду родительская папка шаблона, хотя по существу текущая это последняя, с которой работали.

По вопросам из тем форума, личку не читаю.

 

KonstantinK

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

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

#26

28.01.2019 21:05:51

Цитата
Андрей VG написал:
Как определить это своё место, каков критерий?Если не устраивает Документы, то такой вариантКод ? 1Application.Dialogs(xlDialogSaveAs).Show Environ$(«Temp»)

Критерий простой текущая папка — папка где лежит шаблон. Константы нет.
А вот код. Значит можно указать в диалоговом окне «сохранить как» предустановленный путь из VBA. Этот код рабочий. Открывается не папка «Документы» а «Temp». Значит как-то можно назначить и другую?
«Excel может ВСЁ!» — я тоже отталкиваюсь от этого принципа.

Кто хочет — ищет способы, кто не хочет — причины (Сократ)

 

Андрей VG

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

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

Excel 2016, 365

#27

28.01.2019 21:10:52

Цитата
KonstantinK написал:
текущая папка — папка где лежит шаблон.

Чудненько. Следующий шаг — как ваш код определяет, где лежит этот самый шаблон?

 

Ігор Гончаренко

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

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

#28

28.01.2019 21:18:49

Код
Application.Dialogs(xlDialogSaveAs).Show CurDir

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

Дмитрий(The_Prist) Щербаков

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

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

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

#29

28.01.2019 21:26:58

Цитата
KonstantinK написал:
Значит как-то можно назначить и другую?

можно. Но Вам для начала надо понять КАКУЮ. Если его расположение дефолтное — то можно определить так:

Код
application.TemplatesPath

Если же нет — то тут засада. Не помню, чтобы где-то в Excel или в самой книге это хранилось. Надо искать.

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

 

KonstantinK

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

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

#30

28.01.2019 21:35:53

Цитата
Андрей VG написал:
Чудненько. Следующий шаг — как ваш код определяет, где лежит этот самый шаблон?

Ни как. Я не программист. Пробовал разные варианты с форумов. Все рабочие, но не для шаблона. Если я правильно понимаю, то любой файл Excel (с соответствующим расширением которое знает Windows ) открывается оболочкой Microsoft Office, установленной на компьютере. Затем эта оболочка открывает архив — файл Excel в котором находится вся информация с данными, форматирование, картинками, музыкой и т.д. Т.е. Windows — Microsoft Office Excel — архив/шаблон. Так вот оболочка понимает где лежит мой шаблон/архив. Значит можно определить как-то и нам? Или я что-то понимаю не правильно.

Кто хочет — ищет способы, кто не хочет — причины (Сократ)

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