ListBox 控件、DataObject 对象、MouseMove 事件、StartDrag 和 SetText 方法示例

以下示例演示了通过使用 DataObject 包含拖动的文本从一个 ListBox 到另一个 ListBox 的拖放操作。 此代码示例使用 MouseMove 事件中的 SetTextStartDrag 方法实现拖放操作。

若要使用此示例,请将此示例代码复制到窗体的声明部分。 确保该窗体包含两个分别名为 ListBox1 和 ListBox2 的 ListBox。 您还需要向第二个 ListBox 添加选项。

Private Sub ListBox2_BeforeDragOver(ByVal Cancel As _ 
 MSForms.ReturnBoolean, ByVal Data As _ 
 MSForms.DataObject, ByVal X As Single, _ 
 ByVal Y As Single, ByVal DragState As Long, _ 
 ByVal Effect As MSForms.ReturnEffect, _ 
 ByVal Shift As Integer) 
 Cancel = True 
 Effect = 1 
End Sub 
 
Private Sub ListBox2_BeforeDropOrPaste(ByVal _ 
 Cancel As MSForms.ReturnBoolean, _ 
 ByVal Action As Long, ByVal Data As _ 
 MSForms.DataObject, ByVal X As Single, _ 
 ByVal Y As Single, ByVal Effect As _ 
 MSForms.ReturnEffect, ByVal Shift As Integer) 
 Cancel = True 
 Effect = 1 
 ListBox2.AddItem Data.GetText 
End Sub 
 
Private Sub ListBox1_MouseMove(ByVal Button As _ 
 Integer, ByVal Shift As Integer, ByVal X As _ 
 Single, ByVal Y As Single) 
 Dim MyDataObject As DataObject 
 If Button = 1 Then 
 Set MyDataObject = New DataObject 
 Dim Effect As Integer 
 MyDataObject.SetText ListBox1.Value 
 Effect = MyDataObject.StartDrag 
 End If 
End Sub 
 
Private Sub UserForm_Initialize() 
 For i = 1 To 10 
 ListBox1.AddItem "Choice " _ 
 & (ListBox1.ListCount + 1) 
 Next i 
End Sub

支持和反馈

有关于 Office VBA 或本文档的疑问或反馈? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。