Seleccione el elemento ListBox haciendo clic con el botón derecho en Word VBA

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.

Encontré esta respuesta 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.


preguntado el 01 de febrero de 12 a las 14:02

1 Respuestas

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 a 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
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

Respondido 01 Feb 12, 19:02

Wow, this is pretty cool. Thank you very much for your fast and competent answer. A short test showed exactly the desired result. - Philipp Gfeller

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.