ListBox 控件、DataObject 对象、MouseMove 事件、StartDrag 和 SetText 方法示例ListBox control, DataObject object, MouseMove event, StartDrag, SetText methods example

下面的示例演示如何通过使用**DataObject** 包含拖动的文本, 从一个 ListBox 到另一个**ListBox** 的拖放操作。The following example demonstrates a drag-and-drop operation from one ListBox to another by using a DataObject to contain the dragged text. 此代码示例使用**MouseMove** 事件中的**SetText** 和**StartDrag** 方法来实现拖放操作。This code sample uses the SetText and StartDrag methods in the MouseMove event to implement the drag-and-drop operation.

若要使用此示例,请将此示例代码复制到窗体的声明部分。To use this example, copy this sample code to the Declarations portion of a form. 确保该窗体包含两个分别名为 ListBox1 和 ListBox2 的 ListBoxMake sure that the form contains two ListBox controls named ListBox1 and ListBox2. 您还需要向第二个 ListBox 添加选项。You also need to add choices to the second 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

支持和反馈Support and feedback

有关于 Office VBA 或本文档的疑问或反馈?Have questions or feedback about Office VBA or this documentation? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.