vba 使用 Windows 资源管理器获取要存储在表中的文件的路径(字符串)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11398583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 16:48:45  来源:igfitidea点击:

Using Windows Explorer to get path(string) of a file to store in a table

ms-accessvbams-access-2007

提问by Scotch

I currently have a database set up to store the paths of pictures associated with my data and display them in imageframes with VBA. It works great, but the process of adding a picture is a bit tedious, and users struggle to use it correctly(type the wrong path, forget to include the extension, etc). This results in a bunch of garbage entries in the database. I would like to simplify this process. Ideally, when "add picture" is clicked, I would like for it to open up windows explorer, have the user select the desired picture, get the path of that picture, and insert it into the table. Again, I'm not using an OLE, just a text field for the path. Is this possible?

我目前设置了一个数据库来存储与我的数据关联的图片的路径,并使用 VBA 将它们显示在图像帧中。效果很好,但是添加图片的过程有点乏味,用户很难正确使用它(输入错误的路径,忘记包含扩展名等)。这会导致数据库中出现一堆垃圾条目。我想简化这个过程。理想情况下,当单击“添加图片”时,我希望它打开 Windows 资源管理器,让用户选择所需的图片,获取该图片的路径,并将其插入表格中。同样,我没有使用 OLE,只是路径的文本字段。这可能吗?

采纳答案by Scotch

As Remou referenced, the FileDialog object can be used to accomplish this. For many people, it may be necessary to add references to the MS Office Object Library(The Access Library is not sufficient). The code that I used to collect a path name from a file selected in explorer is as follows:

正如 Remou 所引用的,FileDialog 对象可用于完成此操作。对于许多人来说,可能需要添加对 MS Office 对象库的引用(访问库是不够的)。我用来从资源管理器中选择的文件中收集路径名的代码如下:

 Public Sub ShowFileDialog()
 Dim dlgOpen As FileDialog
 Set dlgOpen = Application.FileDialog(msoFileDialogOpen)
 With dlgOpen
 .AllowMultiSelect = False
 .InitialFileName = "Z:\" 'Initial Path when explorer is opened
 .Show
     If .SelectedItems.Count = 0 Then
       MsgBox ("No file Selected") 'No file selected
     Else
        Me.txtPath = .SelectedItems(1) 'sets textbox on the form to the path selected
     End If
  End With


 End Sub