Is there a way for DIR(path) in VBA to handle strings longer than 260?

后端 未结 5 784
渐次进展
渐次进展 2020-12-06 06:54

Given the following snippet:

Dim s As String: s = \"S:\\vic\\bla\\[..insert more here..]\\data.xml\"
Debug.Print Len(s)
Debug.Print Dir(s)

5条回答
  •  伪装坚强ぢ
    2020-12-06 07:10

    Since I couldn't post a reply to the comment that had the deepfileexists code, here is the code modified so that you can find network paths (since he replied he had a network location)

    You need a function that calls system32 to do a direct path to a network drive. I got the code from here

    heres the code, insert the private function at the top of the module or it wont work. it keeps the function tied specifically to that module, if you want to open it up to the whole workbook drop the private off.

    Private Declare Function SetCurrentDirectoryA Lib "kernel32" _
        (ByVal lpPathName As String) As Long
    

    then heres the function with the modified code to accept that for when there's a network drive starting with \

    Function deepFileExists(longFileName As String)
    ' slowly make your way to the deepest folder...
    ' assuming "\" is used as separator
    ' you could add some code to replace "/" with "\"...
    
    
    Dim pathFragment As String, currentDir As String
    Dim slash As Integer, lastSlash As Integer
    
    If Left(longFileName, 2) = "\\" Then
        slash = InStr(3, longFileName, "\")
        Else
        slash = InStr(1, longFileName, "\")
    End If
    
    lastSlash = 0
    
    pathFragment = Mid(longFileName, 1, slash - 1)
    
    currentDir = CurDir        ' save the current directory
    If Not Left(pathFragment, 2) = "\\" Then
        ChDrive pathFragment       ' making sure we have the right drive
        ChDir pathFragment & "\"   ' be at the root of this drive's directory
        Else
            SetCurrentDirectoryA (pathFragment)
    End If
    
    lastSlash = slash
    slash = InStr(slash + 1, longFileName, "\")
    
    While (slash > 0)
        pathFragment = ".\" & Mid(longFileName, lastSlash + 1, slash - lastSlash)
        If Not Left(longFileName, 2) = "\\" Then
            ChDir pathFragment
        Else
            SetCurrentDirectoryA (pathFragment)
        End If
        'MsgBox "changing directory to " & pathFragment
        lastSlash = slash
        slash = InStr(slash + 1, longFileName, "\")
    Wend
    
    ' now we can look for the file:
    Dim a As String
    Dim something As String
    something = Mid(longFileName, lastSlash + 1)
    
    a = Dir(something)
    If Len(a) > 0 Then
        deepFileExists = True
    Else
        deepFileExists = False
    End If
    
    End Function
    

提交回复
热议问题