Select ListBox item on rightclick in Word VBA

2019-05-21 04:06发布

问题:

I'm developping a project in Word 2003 with VBA. I have a multiselect ListBox with some entries (dates). On rightclick I'd like to have an InputBox popping up where the user can change the selected date. This works well, as long a specific item is already focused (not only selected, but focused). But, if you rightclick on an item without focus, the box shows up and changes the date of the focused entry, not always the one you rightclicked.

I found this answer (http://www.vbarchiv.net/tipps/tipp_920-rechtsklick-in-der-standard-listbox-erkennen.html) but it's not possible in VBA. Has anyone a solution for VBA?

I actually need to change the focused item on rightclick, before the box shows up.

Thank you

回答1:

This is usually done with Hit Testing which Listboxes don't support, here is a hacky way;

Add another listbox called lbTest somewhere on the form, double click its BorderStyle property until it looks like an empty white box, set its visible to false

Private LBI_HEIGHT As Long

Private Sub UserForm_Initialize()
   'get the height of a single list item in twips based on the fact the box will resize itself automatically;
   With lbTest
       .Width = 100
       .Height = 1
       .AddItem "X"
       LBI_HEIGHT = .Height
   End With

   'add test data
   Dim i As Long
   For i = 1 To 50
       ListBox1.AddItem "item " & i
   Next
End Sub

Private Sub ListBox1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
   'get the item at the Y coord based on the scroll position & item height
   Dim derivedIndex As Long
   derivedIndex = (Y \ LBI_HEIGHT) + ListBox1.TopIndex

   Me.Caption = derivedIndex & " = " & ListBox1.List(derivedIndex)
End Sub