本文介绍了VBA中的DIR(路径)是否有方法来处理长于260的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如果 Len(s)> = 260 我收到一条错误,说明以下内容:

 运行时错误'53':

找不到文件

如果字符串小于260,则可以正常工作,并显示找到的和未找到的文件的预期行为。



有没有使用长(> 260)路径名的DIR?



注意




  • 文件重组不是一个选项


  • 我正在Excel 2007中运行



解决方案

这里是一些应该工作的代码,无论深度如何...
基本上,它指定相对路径 - 所以你永远不要调用 dir 用一个长字符串

 函数deepFileExists(longFileName As String)
'慢慢地到达最深的文件夹...
'假设\用作分隔符
'你可以添加一些代码将/替换为\...

Dim pathFragment As String,currentDir As String
Dim slash As Integer,lastSlash As Integer

slash = InStr(1,longFileName,\)
lastSlash = 0

pathFragment = Mid(longFileName,1,slash - 1)

currentDir = CurDir '保存当前目录
ChDrive pathFragment'确保我们有正确的驱动器
ChDir pathFragment& \'位于此驱动器目录的根目录

lastSlash = slash
slash = InStr(斜杠+ 1,longFileName,\)

While(slash> 0)
pathFragment =.\& Mid(longFileName,lastSlash + 1,斜杠 - lastSlash)
ChDir pathFragment
'MsgBox将目录更改为& pathFragment
lastSlash = slash
slash = InStr(斜杠+ 1,longFileName,\)
Wend

'现在我们可以查找文件:
Dim a
a = Dir(Mid(longFileName,lastSlash + 1))
如果Len(a)> 0然后
deepFileExists = True
Else
deepFileExists = False
如果

结束函数


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)

If Len(s) >= 260 I receive an error stating the following:

Run-time error '53':

File not found

If the string is less than 260 it works fine and displays expected behavior for both found and non-found files.

Is there to get DIR working with long (>260) path names?

Notes

  • File restructure is not an option

  • I am running this in Excel 2007

解决方案

Here is some code that ought to work regardless of the depth...Basically, it specifies relative paths - so you never call dir with a long string

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

slash = InStr(1, longFileName, "\")
lastSlash = 0

pathFragment = Mid(longFileName, 1, slash - 1)

currentDir = CurDir        ' save the current directory
ChDrive pathFragment       ' making sure we have the right drive
ChDir pathFragment & "\"   ' be at the root of this drive's directory

lastSlash = slash
slash = InStr(slash + 1, longFileName, "\")

While (slash > 0)
  pathFragment = ".\" & Mid(longFileName, lastSlash + 1, slash - lastSlash)
  ChDir pathFragment
  'MsgBox "changing directory to " & pathFragment
  lastSlash = slash
  slash = InStr(slash + 1, longFileName, "\")
Wend

' now we can look for the file:
Dim a
a = Dir(Mid(longFileName, lastSlash + 1))
If Len(a) > 0 Then
  deepFileExists = True
Else
  deepFileExists = False
End If

End Function

这篇关于VBA中的DIR(路径)是否有方法来处理长于260的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 11:15