|
|
|
Популярные разделы FAQ: Общие вопросы
Особенности VBA-кода
Оптимизация VBA-кода
Полезные ссылки
1. Старайтесь при создании темы указывать в заголовке или теле сообщения название офисного приложения и (желательно при работе с Office 95/97/2000) его версию. Это значительно сократит количество промежуточных вопросов.
2. Формулируйте вопросы как можно конкретнее, вспоминая (хотя бы иногда) о правилах ВЕЛИКОГО И МОГУЧЕГО РУССКОГО ЯЗЫКА, и не забывая, что краткость — сестра таланта.
3. Не забывайте использовать теги [сode=vba] …текст программы… [/code] для выделения текста программы подсветкой!
4. Темы с просьбой выполнить какую-либо работу полностью за автора здесь не обсуждаются и переносятся в раздел ПОМОЩЬ СТУДЕНТАМ.
путь к папке Мои Документы
, Excel VBA
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
Full Member Рейтинг (т): 18 |
Как найти путь к папке «Мои документы» (если она не находится в папке C:Documents and Settingsuser)? |
pashulka |
|
Full Member Рейтинг (т): 95 |
iMyDocuments = CreateObject(«WScript.Shell»).SpecialFolders(«MyDocuments») SpecialFolders Property iMyDocuments = CreateObject(«Shell.Application»).NameSpace(5).Items.Item.Path |
Krasnaja Shapka |
|
Full Member Рейтинг (т): 18 |
сенкс! |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- VB for Application
- Следующая тема
[ Script execution time: 0,6041 ] [ 16 queries used ] [ Generated: 14.04.23, 00:18 GMT ]
I need a Language independent way to get «My Documents» folder in VBA Excel 2003.
What I have:
Public Function MyDocsPath() As String
MyDocsPath = Environ$("USERPROFILE") & "My Documents"
End Function
Because the program will be used in at least 2 lang MS Windows, and the «My Documents» name changes for each language.
Is there a way, or should I try to figure out the system lang and become specific?
asked Oct 13, 2011 at 8:39
Diego CastroDiego Castro
3,4384 gold badges35 silver badges42 bronze badges
This may suit:
Set WshShell = CreateObject("WScript.Shell")
strDocuments = WshShell.SpecialFolders("MyDocuments")
From: http://msdn.microsoft.com/en-us/library/0ea7b5xe.aspx
Although the special folder name is MyDocuments, it refers to the documents folder for several versions of Windows.
answered Oct 13, 2011 at 8:56
1
You may use «Documents», as the localized versions point to the same location.
' Application.PathSeparator can be used, but this
' is unlikely to work on non-Windows environments
MyDocsPath = Environ$("USERPROFILE") & "Documents"
(Seeing that this is a 10 years old question it may not have been the case back then.
answered May 5, 2021 at 8:28
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 lstrlenW Lib “kernel32” _
(ByVal lpString As Long) As LongPrivate 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 LongFunction 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:
Function GetSpecialFolderNames()
Dim objFolders As Object
Set objFolders = CreateObject(“WScript.Shell”).SpecialFoldersMsgBox 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?
-
-
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!
-
-
To be sure, the code should probably look like the following (it’s missing an extra “\” &
Public Function MyDocsPath() As String
MyDocsPath = Environ$(«USERPROFILE») & «\» & «My Documents«
End Function
WIthout the extra bit in there, your path will be returned as “C:Documents & SettingsuserMy Documents” or “C:UsersuserDocuments”
-
his technique is not valid for any newer OS, XP and prior maybe, but Vista, Win7, Win8 the code fails since MS renamed My Documents to just Documents (nothing like MS to throw a wrench in the spokes of it’s own system and screw over developer’s in the process). The only reliable method is to use an API or WScript to get the path of any Special Folder. The other potential issue is that Environ values can be hacked, so it is possible for a user to manipulate your code, better once again with the API/WScript technique.
-
Thanks Mike Alexander. Your Wscript works perfect
-
-
& is just a posting glitch – just remove the “amp;” portion, so you get instead “If SHGetFolderPath(&H0, &H5, -1, &H0, sBuffer) = 0 Then”.
What’s killing me is the next line – the bloody thing just won’t compile – instead I get a Type Mismatch centered on ‘StrPtr’ every time I try to compile.
-
@Frothingslosh If you’re using 64 bit Office, StrPtr returns a LongPtr, not a Long. So
Private Declare Function lstrlenW Lib «kernel32» _
(ByVal lpString As Long) As LongPtr
should work.
-
Actually, mine continues to error on StrPtr, despite the function already being declared a LongPtr. Trying to figure out why, but there isn’t a lot of solid documentation I’ve found yet on the interwebs.
Also, don’t foget you need the PtrSafe in the Declare Function:
Private Declare PtrSafe Function
-
great post! But two errors:
– plz use simple quotes (ascii 34), instead of your “smart” quotes (ascii 147 and 148) — they break the code.
– you’re missing a backslash. Should be:
Environ$(“USERPROFILE”) & “My Documents”– Note, this code will not work if the location of a library has been changed. Your code will only return the DEFAULT location. Is there a way to get the changed value?
cheers!
-
Fixed. I think the API version that’s linked returns the correct path even if it’s changed.
-
Mike Alexander, THANK you for your WScript Code, worked LIKE A CHARM.
Posting code? Use <pre> tags for VBA and <code> tags for inline.
Leave a Reply
Выбор файлов в VBA Excel. Стандартный диалог Application.GetOpenFilename. Стартовая папка диалога выбора файлов.
Открытие диалога выбора файлов
Открытие диалога для выбора любого файла и записи его полного имени в ячейку «A1»:
Private Sub CommandButton1_Click() Range(«A1») = Application.GetOpenFilename End Sub |
В процессе выполнения этого кода VBA Excel открывается диалог с заголовком по умолчанию «Открытие файла» и возможностью выбора любого файла. При нажатии на кнопку «Открытие» полное имя выбранного файла запишется в ячейку «A1». При нажатии на кнопку «Отмена» или кнопку закрытия формы в ячейку «A1» запишется строка «Ложь».
Открытие диалога с заголовком «Выбор файла»:
Private Sub CommandButton1_Click() Range(«A1») = Application.GetOpenFilename (, , «Выбор файла») End Sub |
Открытие диалога выбора файлов с указанием одного фильтра:
Private Sub CommandButton1_Click() Range(«A1») = Application.GetOpenFilename («Файлы Excel 97-2003,*.xls», , «Выбор файла») End Sub |
Фильтр в этом коде VBA Excel представляет из себя пару: наименование фильтра и строка из знака подстановки «*» с расширением отбираемых файлов, разделенных «,». В данном случае в открытом диалоге будут видны файлы с расширением «.xls». Таких пар может быть несколько, как в следующем примере.
Открытие диалога выбора файлов с указанием трех фильтров файлов:
Private Sub CommandButton1_Click() Range(«A1») = Application.GetOpenFilename _ («Файлы Excel 97-2003,*.xls,Текстовые файлы,*.txt,Рисунки,*.jpg», , «Выбор файла») End Sub |
Выбрать один из фильтров можно из раскрывающегося списка диалога выбора файлов «Тип файлов».
Для справки:
Application.GetOpenFilename («Фильтры», номер, «Заголовок диалога»)
Аргумент номер — это номер по порядку фильтра в списке, отображаемого по умолчанию. Если номер отсутствует или превышает количество фильтров, то по умолчанию отображается первый в списке.
Стартовая папка диалога выбора файлов
При открытии стандартного диалога выбора файлов «Application.GetOpenFilename» по умолчанию, как стартовая, выбирается папка «Мои документы» в Windows XP, «Документы» в Windows 8, но, при желании, можно задать, как стартовую, и любую другую папку.
Для этого можно воспользоваться операторами ChDrive (смена текущего диска) и ChDir (смена текущего каталога). По умолчанию текущим является диск «С» в Windows XP, поэтому, если ваша папка находится на этом диске, то ChDrive можно пропустить.
Пример 1
Проверяем, какая папка является стартовой по умолчанию. При вызове процедуры из первого примера диалог откроется именно на этой папке. Если выбрать файл, в ячейку «A1» запишется полный путь к нему, а при отмене выбора, запишется «Ложь».
Private Sub CommandButton1_Click() Range(«A1») = Application.GetOpenFilename End Sub |
Пример 2
В этом примере кода VBA стартовой назначается папка D:Новая папка
. Если пропустить оператор ChDrive "D"
, то по умолчанию стартовой все-равно останется папка «Мои документы».
Private Sub CommandButton1_Click() ‘Смена текущего диска: ChDrive «D» ‘Смена текущего каталога: ChDir «D:Новая папка» Range(«A1») = Application.GetOpenFilename End Sub |
Пример 3
Здесь стартовой назначается папка, в которой расположен исходный файл Excel с кодом.
Private Sub CommandButton1_Click() ‘Смена текущего диска: ChDrive Left(ThisWorkbook.Path, 1) ‘Смена текущего каталога: ChDir ThisWorkbook.Path Range(«A1») = Application.GetOpenFilename End Sub |
Имя диска может быть любым, в зависимости от имеющегося на вашем компьютере.
Смотрите, как с помощью VBA Excel можно открыть папку в проводнике Windows для просмотра.
Sub Print_Environ()
‘https://forum.sources.ru/index.php?showtopic=219673
iMyDocuments = CreateObject(«WScript.Shell»).SpecialFolders(«MyDocuments»)
iMyDocuments = CreateObject(«Shell.Application»).Namespace(5).Items.Item.Path
‘https://www.cyberforum.ru/visual-basic/thread49338.html
WinDir = Environ(«windir») ‘директория с windows
‘И никаких API!
‘Можно и другие:
a = Environ(«TMP») ‘директория временных файлов TEMP
b = Environ(«BLASTER») ‘координаты звуковой карты
c = Environ(«PATH») ‘пути, объявленные в autoexec.bat
‘Можно обращаться и по номеру. Вот вывод полного списка:
Dim str_Environ As String
Dim i As Long
i = 1
Do
str_Environ = Environ(m)
Debug.Print m & » » & Environ(m)
m = m + 1
Loop Until str_Environ = «»
End Sub