2

我正在设计一个包含许多图像的数据库,因此我决定通过存储它们的路径并将图像控件绑定到该字段来链接到外部文件。这是允许我选择文件并将其存储为字符串的代码:

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
4

1 回答 1

0

这是一个即时窗口会话,它演示了可用于确定所选文件的相对路径的技术...

' 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
于 2016-04-18T17:53:31.290 回答