VBA将文件拖放到用户表单以获取文件名和路径 [英] VBA drag and drop file to user form to get filename and path

查看:103
本文介绍了VBA将文件拖放到用户表单以获取文件名和路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学习一个新技巧,但我不是 100% 确信它在 VBA 中是可能的,但我想我会在这里与大师核实一下.

I'd like to learn a new trick, but I'm not 100% confident it is possible in VBA, but I thought I'd check with the gurus here.

我想做的是避开旧的 getopenfilename 或浏览器窗口(在我们的网络驱动器上设置起始目录真的很困难),我想创建一个 VBA 用户表单,其中用户可以从桌面或表单上的浏览器窗口拖放文件,VBA 将加载文件名和路径.同样,我不确定这是否可能,但如果是这样,或者是否有人在我感激指针之前已经这样做了.我知道如何设置用户表单,但除此之外我没有任何真正的代码.如果有什么我可以提供的,请告诉我.

What I'd like to do is eschew the good-old getopenfilename or browser window (it has been really difficult to get the starting directory set on our network drive) and I'd like to create a VBA user form where a user can drag and drop a file from the desktop or a browser window on the form and VBA will load the filename and path. Again, I'm not sure if this is possible, but if it is or if someone has done it before I'd appreciate pointers. I know how to set up a user form, but I don't have any real code outside of that. If there is something I can provide, let me know.

感谢您的时间和考虑!

推荐答案

我想出了一个方法来实现这一点.据我所知,它只能使用树视图控件来完成.您可能必须右键单击您的工具箱才能找到并添加它.它将在附加控制"或类似的东西下.除了控件之外,您还需要两件事.

I figured out a way to achieve this. As far as I can tell, it can only be done using a treeview control. You may have to right click your toolbox to find and add it. It will be there under "additional controls" or something like that. You'll need two things aside from the control.

UserForm_Initialize 子中,您需要以下代码行来启用拖放:TreeView1.OLEDropMode = ccOLEDropManual:

In the UserForm_Initialize sub you will need the following line of code to enable drag and drop: TreeView1.OLEDropMode = ccOLEDropManual:

UserForm_Initialize()
    TreeView1.OLEDropMode = ccOLEDropManual
End Sub

然后您将需要 Private Sub TreeView1_OLEDragDrop 事件.我省略了所有参数以节省空间.它们应该很容易找到.在那个 sub 中简单地声明一个字符串,可能是 strPath 或类似的东西来保存文件名和路径并设置 strPath = Data.Files(1) ,这将得到用户拖动到 TreeView 控件的文件的文件名和路径.这假设用户一次只拖动一个文件,但据我所知,如果您尝试一下,这应该是可以拖动多个文件的事情.

Then you will need the Private Sub TreeView1_OLEDragDrop event. I've omitted all the parameters to save space. They should be easy enough to find. In that sub simply declare a string, maybe strPath or something like that to hold the file name and path and set strPath = Data.Files(1) and that will get the file name and path of a file that the user drags to the TreeView control. This assumes that the user only drags one file at a time, but as far as I can tell this should be something that can be done dragging multiple files if you experiment with it.

Private Sub TreeView1_OLEDragDrop(Data As MSComctlLib.DataObject, Effect As Long, Button As Integer, Shift As Integer, x As Single, y As Single)
    StrPath = Data.Files(1)
End Sub

您还需要添加对 Microsoft Windows Common Controls 6.0

我还添加了示例代码.

这篇关于VBA将文件拖放到用户表单以获取文件名和路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆