programing

Windows 다운로드 폴더 경로 가져오기

megabox 2023. 10. 31. 20:41
반응형

Windows 다운로드 폴더 경로 가져오기

다운로드 폴더 경로를 알아야 하는 엑셀 VBA 코드가 있습니다.어떻게 하면 되죠?

Downloads 폴더(또한 Documents 및 대부분의 폴더를 폴더 속성을 통해 이동할 수 있으므로 환경 변수는 다음과 같습니다.%USERPROFILE%같은 길을 만드는 데는 쓸모가 없습니다.%USERPROFILE%\Downloads,그리고.WScript.Shell.SpecialFolders다운로드 폴더가 나열되지 않습니다.

등기부 열람을 해야 같은데, 저는 그것에 대해 잘 모르겠어요.

감사합니다!

간단한 솔루션 - 일반적으로 작동합니다.

@assylias님의 댓글입니다.다른 사용자가 언급한 것처럼 사용자가 기본 "다운로드" 위치를 변경한 경우 잘못된 폴더 경로를 제공합니다.

Function GetDownloadsPath() As String
    GetDownloadsPath = Environ$("USERPROFILE") & "\Downloads"
End Function

베스트 솔루션

게시된 답변은 "%USERProfile%"\"을(를) 반환하고 있습니다.다운로드".어떻게 해야 할지 몰라서 아래 기능을 만들었습니다.이렇게 하면 함수로 전환되어 실제 경로를 반환합니다.이렇게 부릅니다.Debug.Print GetCurrentUserDownloadsPath아니면Debug.Print GetCurrentUserDownloadsPath. 레지스트리 키를 읽는 방법을 보여주고 폴더 경로로 레지스트리 키를 찾아준 @s_a에게 감사드립니다.

' Downloads Folder Registry Key
Private Const GUID_WIN_DOWNLOADS_FOLDER As String = "{374DE290-123F-4565-9164-39C4925E467B}"
Private Const KEY_PATH As String = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\"
'
Public Function GetCurrentUserDownloadsPath()
    Dim pathTmp As String

    On Error Resume Next
    pathTmp = RegKeyRead(KEY_PATH & GUID_WIN_DOWNLOADS_FOLDER)
    pathTmp = Replace$(pathTmp, "%USERPROFILE%", Environ$("USERPROFILE"))
    On Error GoTo 0

    GetCurrentUserDownloadsPath = pathTmp
End Function
'
Private Function RegKeyRead(registryKey As String) As String
' Returns the value of a windows registry key.
    Dim winScriptShell As Object

    On Error Resume Next
    Set winScriptShell = VBA.CreateObject("WScript.Shell")  ' access Windows scripting
    RegKeyRead = winScriptShell.RegRead(registryKey)    ' read key from registry
End Function

구글 답을 조금 더 찾았는데...

레지스트리를 읽는 방법은 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

MSDN의 http://msdn.microsoft.com/en-us/library/windows/desktop/dd378457(v=vs.85).aspx 에 따르면 다운로드 폴더에 대한 GUID:

{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에서는 작동하지 않습니다.유니코드 쉐나니건이 2000년도 보다 최근 버전의 오피스에서 작동할지는 모르겠습니다.그것은 예쁘지 않다.

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

코드를 가능한 적게 사용하려면 VBA에서 이 PowerShell One-liner를 실행하면 됩니다.

$downloadsFolder = (New-Object -ComObject Shell.Application).NameSpace('shell:Downloads').Self.Path

.ps1을 실행하는 방법은 여기를 참조하십시오.

또한 하나의 라이너를 내장할 수도 있습니다(그러나 이는 새로운 주제입니다).

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

레지스트리에서 올바른 GUID와 함께 다운로드 폴더를 읽고 결과를 사용자 프로파일 경로와 혼합해 보는 것은 어떨까요?

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

Public Function Replace(strExpression As Variant, strSearch As String, StrReplace As String) As String

    Dim lngStart As Long
    
    If IsNull(strExpression) Then Exit Function
    
    lngStart = 1
    While InStr(lngStart, strExpression, strSearch) <> 0
        lngStart = InStr(lngStart, strExpression, strSearch)
        strExpression = Left(strExpression, lngStart - 1) & StrReplace & Mid(strExpression, lngStart + Len(strSearch))
        lngStart = lngStart + Len(StrReplace)
    Wend

    Replace = strExpression
    
End Function

Function GetDownloadedFolderPath() As String

    GetDownloadedFolderPath = RegKeyRead("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\{374DE290-123F-4565-9164-39C4925E467B}")
    GetDownloadedFolderPath = Replace(GetDownloadedFolderPath, "%USERPROFILE%", Environ$("USERPROFILE"))

End Function

언급URL : https://stackoverflow.com/questions/23070299/get-the-windows-download-folders-path

반응형