引用外部文件时将绝对目录转换为相对路径
Posted
技术标签:
【中文标题】引用外部文件时将绝对目录转换为相对路径【英文标题】:Converting absolute directories to relative paths when referring to external files 【发布时间】:2016-04-18 17:42:42 【问题描述】:我正在设计一个包含许多图像的数据库,因此我决定通过存储它们的路径并将图像控件绑定到该字段来链接到外部文件。这是允许我选择文件并将其存储为字符串的代码:
Public Function ShowFileDialog() As String
Dim objFD As Object
Dim strOut As String
strOut = vbNullString
Set objFD = Application.FileDialog(msoFileDialogOpen)
If objFD.Show = -1 Then
strOut = objFD.SelectedItems(1)
End If
Set objFD = Nothing
ShowFileDialog = strOut
End Function
然后由控制按钮调用:
Private Sub Command128_Click()
Dim strChoice As String
strChoice = ShowFileDialog
If Len(strChoice) > 0 Then
Me.Path = strChoice
Else
'bleh
End If
End Sub
这存储了所选文件的绝对目录,但是我最近意识到我需要存储相对路径,以便当数据库及其相关目录移动到新计算机上时(这很可能发生)这些链接将得到维护。
更新: Hans Up 提供的有用提示使我能够完成这项工作。这是我修改和整理的代码。
Public Function GetPath()
Dim objFD As Object
Dim strOut As String
Dim strAbsolute As String
Dim strFolder As String
Dim strRelativePath As String
strOut = vbNullString
Set objFD = Application.FileDialog(msoFileDialogOpen)
If objFD.Show = -1 Then
strOut = objFD.SelectedItems(1)
End If
Set objFD = Nothing
strAbsolute = strOut
strFolder = CurrentProject.Path & "\"
strRelativePath = Mid(strAbsolute, Len(strFolder) + 1)
If Len(strRelativePath) > 0 Then
Me.Path = strRelativePath
Else
'bleh
End If
End Function
Private Sub Command128_Click()
GetPath
End Sub
【问题讨论】:
你的意思是db文件所在目录的相对路径吗?还是相对于其他目录? DB 文件与我要引用的文件所在的几个文件夹存储在同一目录中。 【参考方案1】:这是一个即时窗口会话,它演示了可用于确定所选文件的相对路径的技术...
' folder where db file resides ...
? CurrentProject.Path
C:\share\Access
strFolder = CurrentProject.Path & Chr(92)
? strFolder
C:\share\Access\
' strChoice is the file path from your code sample;
' use Mid() to get the piece from that string which follows strFolder ...
strChoice = "C:\share\Access\image\foo.png"
strRelativePath = Mid(strChoice, Len(strFolder) + 1)
? strRelativePath
image\foo.png
' combine base folder and relative path again just to confirm we got the right pieces ...
? strFolder & strRelativePath
C:\share\Access\image\foo.png
【讨论】:
这非常有帮助!谢谢!以上是关于引用外部文件时将绝对目录转换为相对路径的主要内容,如果未能解决你的问题,请参考以下文章