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