获取Windows下载文件夹的path

我有一些Excel VBA代码,需要知道下载文件夹path。 我怎么能这样做?

由于您可以在Downloads文件夹(以及文档和大多数文件夹,通过文件夹属性)中移动,所以像%USERPROFILE%这样的环境variables是无用的,可以构build一个类似%USERPROFILE%\Downloads的path,而WScript.Shell.SpecialFolders不会列出下载文件夹。

我想这一定是读完registry ,但我对此毫无头绪。

谢谢!

Solutions Collecting From Web of "获取Windows下载文件夹的path"

找到答案谷歌更多一点…

根据http://vba-corner.livejournal.com/3054.html ,阅读注册表的方式如下:

 'reads the value for the registry key i_RegKey 'if the key cannot be found, the return value is "" Function RegKeyRead(i_RegKey As String) As String Dim myWS As Object On Error Resume Next 'access Windows scripting Set myWS = CreateObject("WScript.Shell") 'read key from registry RegKeyRead = myWS.RegRead(i_RegKey) End Function 

和下载文件夹的GUID,根据MSDN的http://msdn.microsoft.com/en-us/library/windows/desktop/dd378457(v=vs.85).aspx :

{374DE290-123F-4565-9164-39C4925E467B}

因此RegKeyRead("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\{374DE290-123F-4565-9164-39C4925E467B}")产生当前用户的下载文件夹路径。

支持读取这种路径的方法是使用SHGetKnownFolderPath函数。

我写了这个VBA代码来做到这一点。 它已经在Excel 2000中测试过了。

它不适用于任何64位版本的Office。 我不知道它的Unicode shenanigans是否可以在比2000版本更新的Office版本上工作。这不太好。

 Option Explicit Private Type GuidType data1 As Long data2 As Long data3 As Long data4 As Long End Type Declare Function SHGetKnownFolderPath Lib "shell32.dll" (ByRef guid As GuidType, ByVal flags As Long, ByVal token As Long, ByRef hPath As Long) As Long Declare Function lstrlenW Lib "kernel32.dll" (ByVal hString As Long) As Long Declare Sub CoTaskMemFree Lib "ole32.dll" (ByVal hMemory As Long) Declare Sub RtlMoveMemory Lib "ntdll.dll" (ByVal dest As String, ByVal source As Long, ByVal count As Long) 'Read the location of the user's "Downloads" folder Function DownloadsFolder() As String ' {374DE290-123F-4565-9164-39C4925E467B} Dim FOLDERID_Downloads As GuidType FOLDERID_Downloads.data1 = &H374DE290 FOLDERID_Downloads.data2 = &H4565123F FOLDERID_Downloads.data3 = &HC4396491 FOLDERID_Downloads.data4 = &H7B465E92 Dim result As Long Dim hPath As Long Dim converted As String Dim length As Long 'A buffer for the string converted = String$(260, "*") 'Convert it to UNICODE converted = StrConv(converted, vbUnicode) 'Get the path result = SHGetKnownFolderPath(FOLDERID_Downloads, 0, 0, hPath) If result = 0 Then 'Get its length length = lstrlenW(hPath) 'Copy the allocated string over the VB string RtlMoveMemory converted, hPath, (length + 1) * 2 'Truncate it converted = Mid$(converted, 1, length * 2) 'Convert it to ANSI converted = StrConv(converted, vbFromUnicode) 'Free the memory CoTaskMemFree hPath 'Return the value DownloadsFolder = converted Else Error 1 End If End Function 
 Sub GetDownloadedFolderFiles() ' ' Keep it simple - Paul Seré ' Dim fso As New FileSystemObject Dim flds As Folders Dim fls As Files Dim f As File 'Downloads folder for the actual user! Set fls = fso.GetFolder("C:\Users\User\Downloads").Files For Each f In fls Debug.Print f.Name Next End Sub