vba 在 MS Excel 中监听鼠标(拖放)事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10520513/
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:05:53  来源:igfitidea点击:

Listening for mouse (drag-and-drop) events in MS Excel

exceleventsvbaexcel-vbadrag-and-drop

提问by freedayum

Is there a way to recognize a drag and drop event on a MS Excel sheet? What I am looking for is to be able to listen to the event when you drag and drop a file (say from desktop) onto a cell in a MS Excel sheet (and have the file's name inserted into the cell).

有没有办法识别 MS Excel 工作表上的拖放事件?我正在寻找的是当您将文件(例如从桌面)拖放到 MS Excel 工作表中的单元格(并将文件名插入到单元格中)时,能够监听事件。

Can this be achieved at all with Excel Macros?.

这可以用 Excel 宏来实现吗?。

回答by HymanOrangeLantern

I myself was unsure how to perform the task - however, it appears someone has already attempted to tackle the issue. I pulled this code from vbadud.blogspot:

我自己不确定如何执行任务 - 但是,似乎有人已经尝试解决这个问题。我从vbadud.blogspot 中提取了这段代码:

' Place file on textbox to display filename.
Private Sub TextBox1_OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single)

' Declare variable(s).
Dim eventvar1 As Integer '* Files Counter

' If an error occurs, go to the Error Handler.
On Error GoTo Error_Handle1
'Drag N' Drop Event Handler
If Data.GetFormat(vbCFFiles) = True Then
eventvar1 = Data.Files.Count
    If eventvar1 = 1 Then
        If InStr(1, LCase$(Data.Files(eventvar1)), ".xls") Then
            txtExcel.Text = Data.Files(eventvar1)
        End If
    End If
End If

   ' Error Handler
    Error_Handle1:
        If Err <> 0 Then
            Debug.Assert Err = 0
            Err.Clear
        End If
    End Sub

The code will post the name of the file if it is put into the textbox. You can use a method, function or even a separate subroutine to make use of the text which has been placed into the textbox.

如果将文件放入文本框中,代码将发布文件的名称。您可以使用方法、函数甚至单独的子程序来使用已放入文本框中的文本。

For instance, examining an SO articleon copying text from a textbox to a cell, you can use this code to input the text into a range on your excel sheet:

例如,检查一篇关于将文本从文本框复制到单元格的SO 文章,您可以使用此代码将文本输入到 Excel 工作表上的范围中:

Range("A2").End(xlDown).Offset(1, 0).Value = TextBox1.Text 

From there, its a matter of either tying the subroutines to another macro for one form of automation or another, dragging and dropping as you see fit, or whatever makes sense for you.

从那里开始,它要么将子程序绑定到另一个宏以实现一种或另一种形式的自动化,拖放您认为合适的,或任何对您有意义的事情。

Let me know if that helps,

如果这有帮助,请告诉我

~JOL

~JOL