我有这个函数,通过将它们转换为绝对路径来处理相对路径。
Public Function ifRelativeConvertToAbsolutePath(path As String) As String
If (isPathRelative(path)) Then
ifRelativeConvertToAbsolutePath = convertToAbsolutePath(path)
Else
ifRelativeConvertToAbsolutePath = path
End If
End Function
我如何实现isPathRelative
功能?
我的想法包括:
答案 0 :(得分:3)
还有一个shell API(PathIsRelative
),或者有PathCombine
,如果收到一个,它会自动将rel路径转换为abs路径;
Private Declare Function PathCombine Lib "shlwapi.dll" Alias "PathCombineA" (ByVal szDest As String, ByVal lpszDir As String, ByVal lpszFile As String) As Long
Dim sBuff As String * 255
PathCombine sBuff, "C:\theroot\xxx\", "..\jibblets"
x = Left$(sBuff, InStr(1, sBuff, vbNullChar) - 1)
== "C:\theroot\jibblets"
PathCombine sBuff, "C:\theroot\xxx\", "X:\foo.bar"
== "X:\foo.bar"
答案 1 :(得分:2)
检查它是否以“\”开头(包括UNC的“\”)或1个字母+“:”
Function IsPathRel(p As String) As Boolean
IsPathRel = Not ((Left(p, 3) Like "[A-Z]:\") Or (Left(p, 1) = "\"))
End Function
答案 2 :(得分:2)
如果您执行以下操作会怎样:
If not Dir( thisWorkbook.Path & "\" & path, vbDirectory) = vbNullString then
ifRelativeConvertToAbsolutePath = thisWorkbook.Path & "\" & path
else
ifRelativeConvertToAbsolutePath = path
end if
基本上,尝试连接路径。如果它产生一个有效的路径,那么它是一个相对路径,你只是修复它,如果它没有产生一个有效的路径,那么你不能使用该方法来修复路径,所以只需按原样返回路径。