programing

vba를 사용하여 현재 작업 디렉터리를 가져오는 방법은 무엇입니까?

topblog 2023. 5. 13. 08:41
반응형

vba를 사용하여 현재 작업 디렉터리를 가져오는 방법은 무엇입니까?

MS Excel 2010을 사용하고 있으며 아래 코드를 사용하여 현재 디렉터리를 얻으려고 합니다.

    path = ActiveWorkbook.Path

하지만 액티브 워크북.경로가 비어 있습니다.

Excel 문서를 열 때D:\db\tmp\test1.xlsm:

  • CurDir()돌아온다C:\Users\[username]\Documents

  • ActiveWorkbook.Path돌아온다D:\db\tmp

그렇게CurDir()에는 시스템 기본값이 있으며 변경할 수 있습니다.

ActiveWorkbook.Path저장된 동일한 워크북에 대해서는 변경되지 않습니다.

예를들면,CurDir()파일/다른 이름으로 저장 명령을 수행하고 파일/디렉토리 선택 대화상자에서 임의의 디렉토리를 선택하면 변경됩니다.그런 다음 저장을 건너뛰려면 취소를 클릭합니다.그렇지만CurDir()마지막으로 선택한 디렉터리로 이미 변경되었습니다.


[ADD] 다른 애플리케이션에 대해 VBA 재개

D:\db\tmp\test1.accdb에 액세스합니다. duckboy81은 다음과 같이 설명했습니다.

  1. CurDir() => C:\Users\[사용자 이름]\문서.
  2. 어플.현재 프로젝트.경로 => D:\db\tmp

Excel D:\db\tmp\test1.xlsm:

  1. CurDir() => C:\Users\[사용자 이름]\문서.
  2. 활성 워크북입니다.경로 => D:\db\tmp
  3. 어플.기본 파일 경로 => C:\Users\[사용자 이름]\문서.

전망:

  1. CurDir() => C:\WINDOWS\System32
  2. 어플.세션.저장(1).파일 경로 => D:\programdata\Outlook\myOutlookDocX.pst

PowerPoint D:\db\tmp\test1.ppt:

  1. CurDir() => C:\Users\[사용자 이름]\문서.
  2. 현재 프레젠테이션.경로 => D:\db\tmp

워드 D:\db\tmp\test1.docx:

  1. CurDir() => C:\Users\[사용자 이름]\문서.
  2. 어플.활성 문서입니다.경로 => D:\db\tmp
  3. 어플.활성 문서입니다.전체 이름 => D:\db\tmp\test1.docx
  4. 어플.시작 경로 => C:\users\[사용자 이름]\appdata\roaming\microsoft\word\startup

찾고 있는 항목에 따라 몇 가지 옵션이 있습니다. Workbook.Path저장된 워크북의 경로를 반환합니다. Application.PathExcel 실행 파일의 경로를 반환합니다. CurDir현재 작업 경로를 반환합니다. 기본값은 My Documents 폴더 또는 이와 유사합니다.

윈도우즈 스크립팅 셸 개체의 를 사용할 수도 있습니다.현재 디렉터리 속성입니다.

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

하지만 그것은 단지 같은 결과를 얻을 것입니다.

Debug.Print CurDir

활성 워크북이 저장되지 않은 것 같습니다.

해라CurDir()대신.

코드:path = ActiveWorkbook.Path

워크북을 아직 저장하지 않았기 때문에 빈칸으로 반환됩니다.

문제를 해결하려면 Excel 시트로 돌아가서 시트를 저장한 다음 코드를 다시 실행합니다.

이번에는 공백으로 표시되지 않지만 위치(현재 폴더)가 표시됩니다.

그게 도움이 되었기를 바랍니다.

사용하다Application.ActiveWorkbook.Path 자체이름 ) 경로 자체에 만 사용할 수 .Application.ActiveWorkbook.FullName워크북 이름이 있는 경로입니다.

탐색기 창에서 현재 경로를 여는 데 사용하는 VBA입니다.

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

Microsoft 설명서:

순수한 작업 디렉토리를 의미하는 경우 적합합니다.

솔루션 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

하지만 그렇지 않다면, 이것으로 충분할 것입니다.

솔루션 B:

Dim ThisWorkbookPath As String

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

아래의 간단한 예:

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

이 코드들을 사용하고 즐겨보세요.

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

여기서 함수를 호출할 수 있습니다.

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

언급URL : https://stackoverflow.com/questions/19824164/how-to-get-current-working-directory-using-vba

반응형