有没有办法识别 MS Excel 工作表上的拖放事件?我正在寻找的是当您将文件(例如从桌面)拖放到 MS Excel 工作表中的单元格上(并将文件名插入到单元格中)时能够监听事件。
这可以通过 Excel 宏来实现吗?
最佳答案
我自己不确定如何执行该任务 - 但是,似乎有人已经尝试解决该问题。我从 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
如果将文件名放入文本框中,代码将发布文件名。您可以使用方法、函数甚至单独的子例程来使用已放入文本框中的文本。
例如,检查 SO article将文本从文本框复制到单元格时,您可以使用以下代码将文本输入到 Excel 工作表的范围中:
Range("A2").End(xlDown).Offset(1, 0).Value = TextBox1.Text
从那里开始,只需将子例程绑定(bind)到另一个宏以实现一种或另一种形式的自动化,根据您认为合适的方式进行拖放,或者进行任何对您有意义的操作。
如果有帮助请告诉我,
~JOL
关于events - 在 MS Excel 中监听鼠标(拖放)事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10520513/