Mousemove vba excel примеры

title keywords f1_keywords ms.prod api_name ms.assetid ms.date

Chart.MouseMove Event (Excel)

vbaxl10.chm500078

vbaxl10.chm500078

excel

Excel.Chart.MouseMove

b1277953-a882-f00f-2ac1-dd0cc49fef72

06/08/2017

Chart.MouseMove Event (Excel)

Occurs when the position of the mouse pointer changes over a chart.

Syntax

expression . MouseMove( Button , Shift , x , y )

expression A variable that represents a Chart object.

Parameters

Name Required/Optional Data Type Description
Button Required Long The mouse button that was released. Can be one of the following XlMouseButton constants: xlNoButton , xlPrimaryButton , or xlSecondaryButton .
Shift Required Long The state of the SHIFT, CTRL, and ALT keys when the event occurred. Can be one of or a sum of values.
x Required Long The X coordinate of the mouse pointer in chart object client coordinates.
y Required Long The Y coordinate of the mouse pointer in chart object client coordinates.

Return Value

Nothing

Remarks

The following table specifies the values for the Shift parameter.

Value Meaning
0 (zero) No keys
1 SHIFT key
2 CTRL key
4 ALT key

Example

This example runs when the position of the mouse pointer changes over a chart.

Private Sub Chart_MouseMove(ByVal Button As Long, ByVal Shift As Long, ByVal X As Long, ByVal Y As Long) 
 MsgBox "X = " &; X &; " Y = " &; Y 
End Sub

See also

Concepts

Chart Object

 

Добрый день, Уважаемые эксперты!  
Требуется ваша помощь по VBA. Мне нужно сделать в форме следующее: при наведении мышью на определённый объект (в моём случае на ComboBox1) нужно, чтобы отобразилась текстовая подсказка (я её разместил на Lable), а после того как мышь с объекта убрана, подсказка должна исчезать.  
Первая часть у меня получилась :-)    
Private Sub ComboBox1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)  
Label46.Visible = True  
End Sub  

  А вот как сделать, чтобы подсказка пропадала, никак додуматься не могу (не очень опытен в VBA).  

  Буду благодарен вам за помощь!

 

а чем вас не устраивает стандартное свойство ControlTepText? Оно есть в списке свойств у ComboBox. Введите туда свой тест и при наведении мыши на ComboBox она будет появляться. Если не хотите руками вписывать это устройство, тобавьте этот код в модуль формы  

  Private Sub UserForm_Initialize()  
   Me.ComboBox1.ControlTipText = «Моя подсказка»  
End Sub

 

прислушайтесь к Павлу..  

  ну а так.. —    

  Private Sub myform_MouseMove(..)  
Label46.Visible = false  
End Sub  

  при этом label46 не должна пересекаться с другими объектами, тогда потеря фокуса label будет синхронна с приобретением фокуса формой.. если же пересечений не избежать, то прописать выключение label для всех таких(пересекающихся) объектов..

 

{quote}{login=Pavel55}{date=08.09.2008 06:18}{thema=}{post}а чем вас не устраивает стандартное свойство ControlTepText? Оно есть в списке свойств у ComboBox. Введите туда свой тест и при наведении мыши на ComboBox она будет появляться. Если не хотите руками вписывать это устройство, тобавьте этот код в модуль формы  

  Private Sub UserForm_Initialize()  
   Me.ComboBox1.ControlTipText = «Моя подсказка»  
End Sub{/post}{/quote}  

    Павел, спасибо большое!  Об этом свойстве я не знал, хотя подозревал, что оно должно быть :-)    
Теперь задача немного усложняется:  
а можно ли сделать, чтобы эта подсказка вылезала для каждого варианта ComboBox (для каждого варианта разная)?

 

Наверное, можно, а что такое «вариант ComboBox»?

 

Лучше покажите на примере (про варианты) )

 

{quote}{login=Pavel55}{date=10.09.2008 12:19}{thema=}{post}Лучше покажите на примере (про варианты) ){/post}{/quote}  

  Вариант — это  я имел ввиду элемент списка ComboBox.

 

{quote}{login=Pavel55}{date=10.09.2008 12:19}{thema=}{post}Лучше покажите на примере (про варианты) ){/post}{/quote}  

  Вот пример

 

эм… я не знаю, как это сделать. Подозреваю, что это можно сделать с помощью WinAPI. Но в нём я не разбираюсь (

 

Я думаю это не сложно, когда вариант в комбобоксе выбран. Примерно так:  
Private Sub ComboBox1_Change()  
Me.ComboBox1.ControlTipText = ComboBox1.Text  
End Sub  

  но в процессе выбора, на выпадающем списке, боюсь не выйдет.

 

Буду дальше ковыряться :-)

 

пока только так получилось..  

  есть закавыки

 

{quote}{login=слэн}{date=11.09.2008 01:05}{thema=}{post}пока только так получилось..  

  есть закавыки{/post}{/quote}  

  Уважаемый, Слэн!  

  Появилось время подумать над этим вопросом. Я столкнулся  с непониманием одной строки (т.к. в VBA я ещё профан).  
Прошу дать пояснения к строке:  
Label50.Caption = ComboBox4.List(Int(Y / 9.65) + ComboBox4.TopIndex)  
Пояснения требуются в связи с тем, что мне требуется адаптировать код к своим задачам.  

  Заранее благодарен!

 

Посмотрите такой вариант — думаю понятнее будет и проще к своим идеям приспособить.  
Int(Y / 9.65) — Y позиция курсора, а все выражение — есть расчет номера строки.  

  2 слэн. Заметил небольшой баг: если больше 8 вариантов, появляется скролл, и позици считается неверно, т.е. больше 8 строки не отдает, что понятно.

 

СердЖиГ

Гость

#15

23.09.2008 09:12:09

{quote}{login=Лузер™}{date=22.09.2008 08:47}{thema=}{post}Посмотрите такой вариант — думаю понятнее будет и проще к своим идеям приспособить.  
Int(Y / 9.65) — Y позиция курсора, а все выражение — есть расчет номера строки.  

  2 слэн. Заметил небольшой баг: если больше 8 вариантов, появляется скролл, и позици считается неверно, т.е. больше 8 строки не отдает, что понятно.{/post}{/quote}  

  Лузер, благодарю.  
Попробую разобраться.

Private Sub
object_MouseMove(ByVal
Button
As Long, ByVal
Shift
As Long, ByVal
X
As Long, ByVal
Y
As Long)

object    An object of type Chart declared with events in a class module. For more information, see Using Events with the Chart Object.

Button    The mouse button that was pressed. Can be one of the following XlMouseButton constants: xlNoButton, xlPrimaryButton, xlSecondaryButton, or xlMiddleButton.

Shift    The state of the SHIFT, CTRL, and ALT keys when the event occurred. Can be one of or a sum of the following values.

Value Meaning
0 (zero) No keys
1 SHIFT key
2 CTRL key
4 ALT key

X    The X coordinate of the mouse pointer in chart object client coordinates.

Y    The Y coordinate of the mouse pointer in chart object client coordinates.

Example

This example runs when the position of the mouse pointer changes over a chart.

Private Sub Chart_MouseMove(ByVal Button As Long, ByVal Shift As Long, ByVal X As Long, ByVal Y As Long)
    MsgBox "X = " & X & " Y = " & Y
End Sub
		

Learn How To Create An Excel Userform Hover-Over Effect

In this article, I am going to explain the process I use to create an emphasis effect on my userforms when the user hovers their mouse over a specific button. You will be able to do this without the need for any additional software and it is very easy to implement once you understand the concept.

Excel VBA Userform Button Hover Effect

Understanding the Hover Concept

Since the built-in CommandButton object for Userforms is highly dated in appearance and has many restrictions in terms of how it can be formatted, I have opted to work with Image Controls for buttons instead. Since images are static and cannot for example change color during run-time, we will be using two images per single button. One image will represent the un-hovered state and the other will represent the hovered state.

The concept is fairly straightforward: we will enact VBA code that will toggle the visibility of the two images based on the location of the users mouse. This will essentially create a toggle button. You can think of it as a curtain we are opening and closing to reveal the actual button behind. The cursor’s position will dictate whether the curtain parts or closes.

Creating The Button Images In Excel

Let’s first create the buttons inside Excel using a textbox. You should already have in mind how you would like your buttons to look. For this example, we will be using “Excel Green” and a basic white/grey format to indicate whether the user is hovering over a particular button.

Things to keep in mind while creating your buttons:

  • What font type and size is your userform using?

  • What font color is your userform using?

  • How big are the controls within your userform?

For the purposes of this tutorial, I am going to assume you are using the default sizes/formatting for the userform control. Below outlines the formats I have chosen to apply to my buttons made out of regular Excel Textboxes.

Build VBA Userform Button Within Excel Spreadsheet

One thing to keep in mind is that the buttons need to be the EXACT SAME SIZE. This means if you have a button with a border, all your buttons will need to possess a border. In my example above, the green buttons do have a 1pt border included, it is just the same color as the fill color, so no visible border appears to the user. This ensures all four buttons will be exactly the same size at the pixel level when we add them to our userform.

Adding Image Buttons To Userforms

In this section, I will walk you through how to get one of the buttons you made in the previous section into a Userform. Throughout this section, you will be interacting a lot with the Properties Pane. If you do not see the Properties Pane when you open the Visual Basic Editor, you can hit the F4 key on your keyboard to make it appear (or the long way would be to navigate to View > Properties Window)

Step 1-2.png

Step 1

Before we begin, you should already have your userform build. I also recommend making the userform’s BackColor white and turning the BackStyle for labels to 0-fmBackStyleTransparent. Those two options can be accessed within the Properties Pane when you select a specific control.

Step 2

Visual Basic Editor Toolbox Dialog

First, we will open up the Toolbox dialog (shown to the right) and insert an Image control. If you do not see the Toolbox floating around your screen within the Visual Basic Editor, you can access it via the View menu and selecting Toolbox. The Image control will appear as a grey box with a dark border once place on your userform.

Step 3-4.png

Step 3

Next, you will want to insert one of the textbox buttons you created into the Image Control. To do this, simply go to your spreadsheet and copy your desired textbox (ctrl + c). Then navigate back to the Visual Basic Editor and select the Image Control. Finally, go to the Properties Pane and click inside the field labeled Picture. Use the keyboard shortcut Ctrl + v and the fields value should change from “(None)” to “(Bitmap)”. You should now see the image appear within the control.

Step 4

To clean up the appearance a little further, go back to the Properties Pane with the Image Control still selected and make the following changes:

  • BorderStyle = 0-fmBorderStyleNone

  • BackStyle = 0-fmBackStyleTransparent

Finally, I recommend tightening up the size of the control to get it as close to the actual image size as possible. I typically leave 1-2 pixels of whitespace between the Image Control’s border and the edges of the image within it.

Step 5-6.png

Step 5

Next, we will begin to make our second button which will represent the inactive (un-hovered) state. Go ahead and copy the Image Control (ctrl + c) and paste it (ctrl +v) somewhere else on your userform.

Step 6

To change the image of this second Image Control, simply redo Step 3 and copy/paste the White Button into it.

Step 7.png

Step 7

Place the White OK button exactly on top of the Green OK button. You can do this by using your mouse or you can input the Top and Left properties within the Properties Pane so that the location of both buttons are exactly the same. If you have Align to Grid turned on (Tools menu > Options > General > Align Controls to Grid), it should be fairly easy to get them on top of each other with the mouse.

Creating A Hover With VBA

To illustrate the hovering technique more clearly, I went ahead and added another button to the userform (shown below). Circling back to the concept of what we are going to be doing here from a VBA front, note we have essentially two white buttons covering up our green, actionable buttons (the buttons the user will actually be clicking with their mouse).

If you think about it, all we need to do is write some VBA that hides the white buttons when the user’s mouse hovers over them. This reveals the desired green button and gives the user the opportunity to click it (think back to the curtain analogy from earlier).

So let’s get into a little VBA coding!

Final Userform UI

MouseMove Event

If you have done any work with Userforms, you know that events are vital to making the user experience feel “normal”. For this effect, we are going to be using the MouseMove event which tracks which pixel on the screen the user’s cursor is currently touching. The moment the cursor moves to a pixel within a specific control, that control’s MouseMove event fires and the code attributed to it begins to run. This is precisely how we will know when to toggle our button images to create the hover effect!

Image Control Names

Before we write any VBA macros, let’s be clear on what I have named the Image Controls for this example. Below are the four names I have attributed to the controls via the Properties Pane > Name field.

CancelButtonInactive = White Cancel Button
OKButtonInactive = White OK Button
CancelButton = Green Cancel Button (This is the real button that will call your VBA macro)
OKButton = Green OK Button (This is the real button that will call your VBA macro)

The OK Button

Below is the VBA code we will attribute to the OKButtonInactive (white OK button) image control. Note that the MouseMove event has a bunch of inputs (Button, Shift, X, Y). We will not be using any of these, however, the will need to be explicitly written as shown below in order for the VBA code to compile properly.

Essentially what the VBA code does is when the user’s cursor hovers over the OKButtonInactive control, it will hide itself, revealing the green OK button underneath of it.

You’ll also notice that the code is also making sure the CancelButtonInactive control is visible. This prevents any risk of the user hopping from the Cancel button to the OK button “turning” both buttons green. This is a very important concept as you will need to be sure you account for all buttons on your userform that are using this hover technique.

Sub OKButtonInactive_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
‘PURPOSE: Make OK Button appear Green when hovered on

  CancelButtonInactive.Visible = True
  OKButtonInactive.Visible = False

End Sub

The Cancel Button

I won’t go into as much detail as the previous section, but the below VBA code is essentially do the exact same thing except for the Cancel Button.

Sub CancelButtonInactive_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
‘PURPOSE: Make Cancel Button appear Green when hovered on

CancelButtonInactive.Visible = False
OKButtonInactive.Visible = True

End Sub

Accounting For No Hovering Action

Up until now, we have assumed either the user’s cursor is on the OK button or the Cancel button. But what if the user has their cursor somewhere else? In that case, we don’t want any of the buttons to appear as green. By using the Userform_MouseMove event, we can essentially reset the userform by making all the white buttons visible. The precise moment the cursor moves off a control and onto the Userform’s background, this VBA code will trigger and change the visibility state of our buttons.

Sub Userform_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
‘PURPOSE: Reset Userform buttons to Inactive Status

CancelButtonInactive.Visible = True
OKButtonInactive.Visible = True

End Sub

Be Careful About Control Proximity

Early on when I was perfecting this technique, I ran into issues when my controls were too close together. Based on your userform’s layout, there may be a risk that you perform what I have coined as “control hopping”. This is where your cursor moves directly from one control to the other without triggering the Userform_MouseMove event. This theoretically shouldn’t happen since the cursor has to move onto the Userforms background if there is even one pixel of space between your control.

What I recommend doing is testing your userform by moving your mouse over it quickly to see if you can trigger a state where multiple buttons appear to be highlighted at the same time. To fix this you can either add extra space between the controls on the screen or add a MouseMove event to that control that runs the exact same code as the Userform_MouseMove subroutine.

You Now Have Hover-Buttons!

If you’ve followed along all the steps, you should now have a functioning userform with buttons that change format every time the cursor hovers over them.

If you are still unclear or would like to see these results in an actual Excel workbook, I have put together a downloadable spreadsheet you can comb through. Feel free to directly download the spreadsheet by clicking the download button below.

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon!

— Chris
Founder, TheSpreadsheetGuru.com

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
LRESULT APIENTRY MainWndProc(HWND hwndMain, UINT uMsg, 
                             WPARAM wParam, LPARAM lParam) 
{ 
    HDC hdc;                       // дескриптор контекста устройства 
    RECT rcClient;                 // прямоугольник рабочей области 
    POINT ptClientUL;              // верхний левый угол рабочей области
    POINT ptClientLR;              // нижний правый угол рабочей области 
    static POINTS ptsBegin;        // исходная точка
    static POINTS ptsEnd;          // новая конечная точка 
    static POINTS ptsPrevEnd;      // предыдущая конечная точка 
    static BOOL fPrevLine = FALSE; // флажок предыдущей линии 
 
    switch (uMsg) 
    { 
       case WM_LBUTTONDOWN: 
 
            // Захват ввода данных от мыши. 
 
            SetCapture(hwndMain); 
 
            // Получим экранные координаты рабочей области, 
            // и преобразуем их в рабочие координаты. 
 
            GetClientRect(hwndMain, &rcClient); 
            ptClientUL.x = rcClient.left; 
            ptClientUL.y = rcClient.top; 
 
            // Добавим по единице с правой и нижней стороны, поскольку 
            // координаты полученные при помощи GetClientRect не 
            // включают в себя крайний левый и крайний нижний пиксели. 
 
            ptClientLR.x = rcClient.right + 1; 
            ptClientLR.y = rcClient.bottom + 1; 
            ClientToScreen(hwndMain, &ptClientUL); 
            ClientToScreen(hwndMain, &ptClientLR); 
 
            // Скопируем рабочие координаты рабочей области в 
            // член rcClient структуры. Ограничим курсор мыши рабочей 
            // областью с помощью передачи rcClient структуры в 
            // функцию ClipCursor. 
 
            SetRect(&rcClient, ptClientUL.x, ptClientUL.y, 
                ptClientLR.x, ptClientLR.y); 
            ClipCursor(&rcClient); 
 
            // Преобразуем координаты курсора в структуру POINTS, 
            // которая определяет исходную точку рисуемой линии 
            // в ходе сообщения WM_MOUSEMOVE. 
 
            ptsBegin = MAKEPOINTS(lParam); 
            return 0; 
 
        case WM_MOUSEMOVE: 
 
            // Когда мышь движется, пользователь, чтобы нарисовать линию, 
            // должен удерживать нажатой левую кнопку мыши. 
 
            if (wParam & MK_LBUTTON) 
            { 
 
                // Получим контекст устройства (DC) для рабочей области. 
 
                hdc = GetDC(hwndMain); 
 
                // Ниже следуют функции гарантирующие, что пиксели  
                // предыдущей нарисованной линии установятся в белый и
                // те же самые новой линии установятся в черный. 
 
                SetROP2(hdc, R2_NOTXORPEN); 
 
                // Если линия была нарисована раньше сообщения WM_MOUSEMOVE 
                // то рисование проходит поверх ее. Линия стирается при помощи 
                // установки ее пикселей в белый цвет. 
 
                if (fPrevLine) 
                { 
                    MoveToEx(hdc, ptsBegin.x, ptsBegin.y, 
                        (LPPOINT) NULL); 
                    LineTo(hdc, ptsPrevEnd.x, ptsPrevEnd.y); 
                } 
 
                // Преобразуем текущие координаты курсора в структуру
                // POINTS, а затем нарисуем новую линию. 
 
                ptsEnd = MAKEPOINTS(lParam); 
                MoveToEx(hdc, ptsBegin.x, ptsBegin.y, (LPPOINT) NULL); 
                LineTo(hdc, ptsEnd.x, ptsEnd.y); 
 
                // Установим флажок предыдущей линии, сохраним конечную 
                // точку новой линии, а затем восстановим прежний DC. 
 
                fPrevLine = TRUE; 
                ptsPrevEnd = ptsEnd; 
                ReleaseDC(hwndMain, hdc); 
            } 
            break; 
 
        case WM_LBUTTONUP: 
 
            // Пользователь закончил рисовать линию. Сбросим флажок 
            //  предыдущей линии, освободим курсор мыши, и освободим 
            // мышь от захвата. 
 
            fPrevLine = FALSE; 
            ClipCursor(NULL); 
            ReleaseCapture(); 
            return 0; 
 
        case WM_DESTROY: 
            PostQuitMessage(0); 
            break; 
 
        // Обработка других сообщений.

Like this post? Please share to your friends:
  • Mouse is not working in word
  • Mouse flashing in word
  • Mountain everest is high mountain in the word
  • Mount everest is mountain in the word
  • Motorhead i don t believe the word tabs