Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  HOME    TRACKER    Visual Basic

Which Shape Was Clicked? (Excel)

Hi, Gang:

I want to use one routine to trap a click on any of several shapes, and
return which shape was clicked, so that I can work with it. I can't
seem to find the equivalent of Worksheet_SelectionChange for shape

Thanks in advance!

Eric Johnson

509-735-4700 x 195

View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
How To Determine Which Shape Was Clicked?

I have lots of shape in a worksheet and I would like to apply the same method to all of them. The problem is that I need the name of the shape I have just clicked on.
do you know how I can determine this name since excel do not allow methods with parameters?

many thanks.

Clicked Excel Sheet

I have a workbook in which 7 worksheets are there. I am in sheet1 and I click some other sheet. Then in the Deactivate function of Sheet1 I have some conditions . If all the conditions are satisfied then I want to move to the other sheet whichever is clicked. For this I want to know which sheet has been clicked.

Anyone help me how to get this clicked sheet? Thanks in advance

VBA In Excel - If Cell A1 Is Clicked, Then Do Something
Hi, I am using the following code to try to do something ONLY when cell A1 is clicked, however, its not working because whenever I clear the value of any cell in the worksheet, it still thinks I clicked cell A1, even though I did not.

Code:Private Sub Worksheet_Change(ByVal Target As Range)

    'If you change cell A1 then...
    If Target = Range("A1") Then

        'What cell did you click on? (This message box should only ever show up when cell "A1" is clicked, and therefore it should always only return "A1")
        MsgBox ("The Target cell you changed is:" & vbCrLf & vbCrLf & _
            "Col=" & Target.Column & vbCrLf & _
            "Row=" & Target.Row)

    End If

End Sub

Now, I noticed that if A1 has a value in it already, and I delete the value in another cell, then this will work as intended (nothing will happen). However if A1 is empty, and I delete the value in another cell, it still executes the code in the If Then.

Please help

Edited by - Latrosicarius on 5/8/2008 12:00:25 PM

Cancel Clicked In Common Dialog In Excel
Is there anyway to test if the user has clicked the cancel button when prompted with a save common dialog in excel...

i would check to see if the file path is empty... but i am giving the user a default save title.. any ideas?

EXCEL: Execute A Macro When A Cell Is Clicked
How can I select a cell in Excel and cause it to activate a macro? I also need to know what the range address is of that activated cell. The macro will open up a userform where the user selects an item and the first column value will be placed in that active cell.

I think I'm in over my head...


Excel Shape Problem! Need Help!
This is how i Create a Excel file and The shapes on it...

Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim xlSheet1 As Excel.Worksheet
Dim xlSheetAdd As Excel.Worksheet

Set xlApp = New Excel.Application
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets.Add
Set xlSheetAdd = xlBook.ActiveSheet
xlSheet.Name = "Sheet"

'xlSheetAdd.Shapes.AddShape(msoShapeRoundedRectangle, 5, 5, 150, 55).Name = "MainItem"
With xlSheetAdd
.Shapes.AddShape(msoShapeRoundedRectangle, 5, 5, 150, 55).Name = "MainItem"
.Shapes.AddTextbox(msoTextOrientationVertical, 10, 10, 140, 15).Name = "MainText"
.Shapes.AddTextbox(msoTextOrientationVertical, 10, 25, 140, 15).Name = "BarCode"
.Shapes.AddTextbox(msoTextOrientationVertical, 10, 40, 140, 15).Name = "ControlNumber"
End With

xlApp.Visible = True

Set xlApp = Nothing
Set xlBook = Nothing
Set xlSheet = Nothing

My problem here is, how can i Edit the shapes that i added? I mean set its caption, backcolor, font? is this possible??

any help will be appreciated...

Excel Shape Objects - PLEASE HELP

If I have a shape object in a cell say "V3". How can I get Excel, using VB, to go to that cell and select the shape or other object contained in it, WITHOUT copying or selecting the whole cell.

ie. I want to enable the user to draw any shape into cell V3 and then my VB script will take the object they have entered into that cell, copy it, and paste it OVER some existing data. Therefore if the entire cell was selected and then pasted it would write over the existing data, which is what I am trying to get round....

Please help....
I wonder if there is a cellContents or Cell.Object.Select method or similar...

Riyaz Assrafally.

Formating A Shape In Excel With A Macro.
Let me start off by saying that I am pretty new to VB. I only know what I have taught myself while working with excel. What I am trying to do is format the color of multiple shapes (specifically ovals from the drawing toolbar) with a single macro. What I need it to do is cycle through 3 colors when clicked. This is easy to do if I just make a macro with a keyboard shortcut and run the macro when the shape I want the formating to chage on is selected, but I want to be able to do this by just clicking on the shape. The problem I am having is that I cannot find out how to specify which shape initated the macro because once you right-click on a shape and assign a macro to run on a click, it does not select it when u click on it anymore. It just runs the macro. Any help would be appreciated.

Inline Shape Excel Objects
I'm writing a Word macro and am trying to insert an Excel object into a Word document. If I do this manually from the word document, it works fine. If I record the macro, or write the VB code to do it, the object is inserted but has been scaled horizontally - ie its been squashed up into the centre by a couple of cm.

The code I'm using is:

Selection.InlineShapes.AddOLEObject ClassType:="Excel.Sheet.8", Filename:=myFilename, LinkToFile:=False, DisplayAsIcon:= False

The spreadsheet I'm trying to insert has been scaled to fit on the page, so I don't want it scaled when it is inserted into the document. I also want it to remain a spreadsheet once in the document.

Does anyone know how to get around the scaling problem, or a better way of inserting the spreadsheet into my document (but still keeping it as a spreadsheet)?

Moving Excel Chart/Shape???
I have the following code that generates an Excel chart on the  worksheet that is passed to it.  The creating of the chart works fine but I am having trouble moving the chart where I want to after it is created.  I am passing several different worksheets through this code and it bugs out after the first sheet because I have not been able to find an effective way telling it which chart/shape I want to move.  Right now I have the shape index manually coded in but only works for the first chart.  Any suggestions would be helpful.

    Public Function addHeaderFooter(ByVal wrksheet As Excel.Worksheet, ByVal headerText As String, ByVal footerText As String)
    With wrksheet

        .PageSetup.Zoom = False
        .PageSetup.CenterHeader = headerText
        .PageSetup.CenterFooter = footerText
        .PageSetup.Orientation = xlLandscape
        .PageSetup.LeftMargin = (0.5)
        .PageSetup.RightMargin = (0.5)

    End With
    End Function
    Public Function createChart(ByRef excelapp As Excel.Application, ByRef wrksheet As Excel.Worksheet, _
    ByVal startRow As Integer, ByVal endRow As Integer)
    Dim eChart As Excel.Chart
    Dim chartName As String
    With wrksheet
    Set eChart = wrksheet.Parent.Charts.Add
    With excelapp
        .ActiveChart.ChartType = xlLineMarkers
        .ActiveChart.SetSourceData wrksheet.Range("G" & (startRow) & ":G" & (endRow) & ", " & "E" & (startRow) & ":E" & (endRow) & "")
        .ActiveChart.SeriesCollection(1).XValues = wrksheet.Range("B" & (startRow) & ":B" & (endRow) & "")
        .ActiveChart.SeriesCollection(1).Values = wrksheet.Range("G" & (startRow) & ":G" & (endRow) & "")
        .ActiveChart.SeriesCollection(1).Name = "=""CWT"""
        .ActiveChart.SeriesCollection(2).Values = wrksheet.Range("E" & (startRow) & ":E" & (endRow) & "")
        .ActiveChart.SeriesCollection(2).Name = "=""WEIGHT"""
        .ActiveChart.Location xlLocationAsObject, wrksheet.Name
        .ActiveChart.SeriesCollection(2).AxisGroup = 2
        chartName = .ActiveChart.Name
    End With
    With excelapp
            With excelapp.Selection
                .Width = 300
                .Height = 130
            End With

    End With
    With excelapp.ActiveChart
        .HasTitle = True
        .ChartTitle.Characters.Text = "CWT"
        .Axes(xlValue, xlPrimary).HasTitle = True
        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "CWT"
        .Axes(xlValue, xlSecondary).HasTitle = True
        .Axes(xlValue, xlSecondary).AxisTitle.Characters.Text = "Weight"
    End With
    With excelapp
        .ActiveChart.HasLegend = True
        .ActiveChart.Legend.Position = xlLegendPositionBottom
    End With
    With wrksheet.Shapes(2)
        .Top = wrksheet.Rows(endRow + 3).Top
        .Left = wrksheet.Columns(1).Left

    End With
    With wrksheet
        .Cells(7, 1).Select
    End With

    Set eChart = Nothing
    End With
    End Function

Detect If Shape Has Text In Excel Or Not?
In word if I use the following code
Code: If Selection.ShapeRange.TextFrame.HasText Then
I can detect if a shape contains text before I try and copy it. However in Excel I can't seem to do the same thing. I've tried the following
Code: If oWbk1.Sheets("EMAIL").Shapes(i).TextFrame.Characters.Text Then...
but it doesn't like that.


Edited by - RicardoSmith on 7/9/2003 8:41:51 AM

Selection Table + Excel Shape (OLE Object)
Hello @ all,

I have a problem bei including an excel file.
SET myExcel = myWord.ActiveDocument.Shapes.AddOLEObject (, "C:ProjectsRechnung emplateexcel.xls")

The excel file is laying over the document!
Is there a code, that I can put the excel file in my table?

Thank you in advance.

Greets from Germany

Can You Implement A Click Shape Event In Excel?
no excel events trip when an opperation is done to a shape. is there a way to implement an event like a click on a shape or a selection change on a shape?



VBA In Excel - How To Copy A Jpg Picture From Shape To UserForm.Image
Hi, becauce I have difficulties with programatically filling UserForm.Image with a jpg file (it is decompressed by Excel and saved probably as bmp later, so that the .xls file gets really big), I would like to copy the image from a hidden Shape placed in the Excel sheet to a UserForm.Image on runtime. Please can anybody tell me how to copy it, if it is possible? Kind regards, Karel Rys

Detect Shape Object Movement Events In VBA Excel
I dynamically create shape objects that I display in an Excel worksheet. Is there a way that I can detect when the shapes are moved when the user drags and drops them? If I set the OnAction property for a shape, then the cursor changes to a hand when it is over the shape, and I can detect a mouse click on the shape, but I cannot drag and drop the shape. If I reset the OnAction property to "" (empty quotes), then I can drag and drop again within the worksheet, but I don't know how to make my VBA app aware that the shapes have been moved.

Does anyone have any ideas? Thanks!

Shape Objects Orbiting Around Single Shape Object
Im trying to create a program that has many circle shape controls that orbit around a single circle shape (Sun), im trying to create our solar system using BitBlt, i just need to know how to generate the shapes to orbit around 1 shape, all help would be appreciated - Cheers

How To Stop The Shape From Flickering(A Shape Control Is Used)
Hello Every1,
I have a peuliar problem for u guys. Follow closely the code given below......

Dim x1 As Single, y1 As Single
Dim draw As Boolean
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
x1 = X
y1 = Y
draw = True
End Sub

Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
If draw = True Then
Shape1.Left = x1
Shape1.Top = y1
Shape1.Width = X - x1
Shape1.Height = Y - y1
End If
End Sub

Private Sub Form_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
draw = False
End Sub

The shape sizes according to our mouse, the only problem is the shape flickers. Can any1 stop that flickering. I'll be really happy if any1 can do it for me. Thank u...

PS: I have tried changing the AutoRedraw & ClipControl options on & off. They dont help...

How Can I Change My Form Shape To Custom Shape
How Can I Change My Form's Shape To Custom Shape when This Shape Is Not Circle,Rectangle Or Othere Standard Shape
For Example One Shape Like "Wndows Media Player XP" When Mouse Is Not On It

please Help Me And Send Answer To This email

Excel VBA, When Cell Is Clicked A &"NO!&" Msg Box Appears.
I found excel file about helping with Sudukos.

Anyway, if the user clicks on any other cell that's not the
Suduko 9 by 9 cell range a message box appears and says
"You can't go there".
I have need of this code.

Also if the user uses the arrows keys and goes out of
bounds of the 9x9 range this msg appears and pops you
back to the top left corner cell.

Bubba Hotep

Making A Shape Follow A Shape
how can i make a shape follow another shape like it's exect path?

Shape-Shape Collision
It's been almost a full year since i last worked in vb and am i having difficulty with the collision of my ball with the blocks (both of which are shapes) in a breakaway style game.

my blocks are contained in a control array, and i tried placing my collision detection in side a For...Next loop. but my problem is getting it to detect which side it hit, so it knows which way to bounce off.

Anyone got any ideas?

Right Clicked Over ???
How do I tell which toolbar the user right clicked over so I can bring up the corresponding popup.
I have an array of toolbars and want to write one routine to cover them all.



If The Button Is Clicked
How can I say If (frmPrices.txt1.Text = "" Or cmd1.Enabled = True) Then
something happens? Except, I'm guessing that enabled doesn't do it. I want it to do something if it is clicked within this if statment. Is this possible?

How To Tell Which Button Was Clicked
I have an array of 10 buttons named cmdPath (0-9). I only want one path form to show up to load images from, but I need to check to see which button was clicked because each button has its own text box with it. So when the file out of the Path form is loaded i need to check to see which array of cmdPath was clicked so that the path of the file selected goes into the correct text box. I hope I'm clear with my question.

To Know When Cancel Was Clicked...
I have a Msg Box, and I want it to be Ok,Cancel. How do program my app to do different things if either button is clicked? Thanks in advance!

Pause Until Ok Is Clicked
The MsgBox() function displays a message in a dialog box, waits for the user to click a button, and returns an Integer indicating which button the user clicked. You are describing the operation of the message box.

How To Know Which Row In A MSHFlex Is Clicked?
I got some data displayed in a MSHFlex grid. Could anybody help me do the following:

When I click on any row (say row number 5) of the MSHFlex, a msgbox will pop up saying row 5 is clicked.


Control Clicked
Is there an API call to get the name of the last control clicked?

I didn't want to have to put code in all MouseDown Events.....

Which Collum Clicked
I have a flexgrid with 5 collums
(1) on click on 1st collum - label1.caption="clicked on 1st collum"
(2) on click on 5th collum - label1.caption="clicked on 5th collum"
(3) when I double click on 1st collum - label1.caption="double clicked on 1st collum"

How it can be done with flexgrid?

Hide When Clicked?
Hy all, again

So I need help for this:

When M>=4 then add.visible = true ( i set that add is invisile by default).
But how to set that when i click on add then add go to invisible, forever?

I set on up: If m.Caption >= 4 Then add.Visible = True
and on add: If add.Enabled Then add.Visible = False

And it's work, when i click on add its become invisible, but when i click on UP, add is visible

So i want this, that add is visible when M>=4 and it's visible all the time when M>=4, EXCEPT when i click on add, when i click on add it need to be invisible forever.

Sry for my english, i hope that you understund me

Listbox Always Gets Clicked
Hi Again,
This is really weird, I have never had this problem before. I am using a simple listbox, but everytime I access it in any way it performs the _Click event. If I to .clear, or set all .selected(i) true or false, or just go thru each item to see which are .selected(i) = true, then my click event is performed. I have set up a true/false flag to get around this, but I shouldn't have to do this????? ANy ideas??

Tell If Command Was Clicked
Hi how would i tell if a command was clicked 3 times.I am trying to make a password protection for my app.I want it to check if the user clicks the command 3 times with the wrong serial it ends.Can someone post an example code thanks.

If A Link Is Right-clicked...
morning all.

Im using the Webbrowser control.
I would like to have different pop-up menus when right-clicking plain text and when right-clicking links...but is that possible?


How To Get Item That Is Right Clicked
how do i know what item is right clicked in a listBox...i've the following code for when item is right clicked:

VB Code:
Private Sub SharedList_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)If Button = vbKeyRButton Then        PopupMenu mnuEdit    End IfEnd Sub Private Sub deleteFile_Click()    SharedList.RemoveItem (0)    'remove from sharedDrag, sharedPath, sharedSizeEnd Sub

How Can I Know When The Clicked Outside Of The Form?

I have a form, and I want to know when the user clicked somewhere outside
the form.
how can I do that using vb?


PictureBox Clicked
Hi there!

I have 10 picture boxes in my form:

How do I know which picture box was clicked? I do not want to have 10 different Sub's:

Private Sub Picture1_Click()
End Sub

to do this.

Thanks in advance.


Know When Max Button Is Clicked?
I put some code in the form resize event so my controls resize with it. But when I click the Maximize button, they do not resize and I do not see an event for this. Any way of detecting this?

I may have missed something right in front of my eyes!


Label That Has Been Clicked...
Hey Everyone
How can we trap click event of any label on the form?

Detecting X Clicked
Is it possible to detect the X in the top right of a window being clicked as opposed to say an Exit Command button being pressed?

What Menu Is Clicked?
after finally finding this code at and downloading there awesome program I finally got this to work and create a menu....but I am having a lot of difficulty figuring out which menu item is click. Here is my code.

VB Code:
'what i declareConst MF_CHECKED = &H8&Const MF_APPEND = &H100&Const TPM_LEFTALIGN = &H0&Const MF_DISABLED = &H2&Const MF_GRAYED = &H1&Const MF_SEPARATOR = &H800&Const MF_STRING = &H0&Private Type POINTAPI    x As Long    y As LongEnd TypePrivate Declare Function CreatePopupMenu Lib "user32" () As LongPrivate Declare Function TrackPopupMenu Lib "user32" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal x As Long, ByVal y As Long, ByVal nReserved As Long, ByVal hwnd As Long, ByVal lprc As Any) As LongPrivate Declare Function GetSystemMenu Lib "user32" (ByVal hwnd As Long, ByVal bRevert As Long) As LongPrivate Declare Function AppendMenu Lib "user32" Alias "AppendMenuA" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal wIDNewItem As Long, ByVal lpNewItem As Any) As LongPrivate Declare Function DestroyMenu Lib "user32" (ByVal hMenu As Long) As LongPrivate Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As LongDim hMenu As Long    'where i want a menu    hMenu = CreatePopupMenu()    AppendMenu hMenu, MF_STRING, ByVal 0&, "Options"    AppendMenu hMenu, MF_STRING, ByVal 0&, "Move"    AppendMenu hMenu, MF_SEPARATOR, ByVal 0&, ByVal 0&    AppendMenu hMenu, MF_STRING, ByVal 0&, "Exit"    Dim Pt As POINTAPI    GetCursorPos Pt    TrackPopupMenu hMenu, TPM_LEFTALIGN, Pt.x, Pt.y, 0, Me.hwnd, ByVal 0&

Now how can i tell which one the user clicks?

Which Control Was Clicked?
I have a form with two flexgrids on it. When either of them is double clicked, I want to bring up one form(the same form is for both grids) and know which was clicked. Is there awat to do this, aside from a control array.

I want something like this


sub grid1_dblclick ()
end sub

sub grid2_dblclick ()
end sub

frm1_load ()
'determine which grid was clicked and process information
end sub

any ideas?

If Button Is Clicked Then....
How do I check if a button is clicked?

When X In Control Box Is Clicked. . .
Whenever I click on the X in the upper right of my form it closes the form, but still leaves it sitting in memory. Why? and is there any way to completely remove it from memory when the X is clicked?

The Button Clicked Before...
Here is another way to implement netSurfer's first idea, only instead of using a global variable, use the Save button's Tag property.

I have found the Tag property to be very useful (especially in control arrays where all controls have the same name and are only differentiated by an index).

Simply set the Tag property (which is a string) of the Save button to the caption of the last button clicked. Do this under the click event of the NewRecord button and the Changes button.

Here's an example:

Option Explicit

Private Sub Form_Load()

'Make sure tag is empty when form loads
cmdSave.Tag = ""

End Sub

Private Sub cmdChanges_Click()

cmdSave.Tag = "Changes"

End Sub

Private Sub cmdNewRecord_Click()

cmdSave.Tag = "NewRecord"

End Sub

Private Sub cmdSave_Click()

If cmdSave.Tag = "Changes" Then
'Put code here that reflects that user
'clicked the "Change" button

ElseIf cmdSave.Tag = "NewRecord" Then
'Put code here that reflects that user
'clicked the "New Record" button

'Put code here that reflects that user
'didn't click either button first

End If

End Sub

Hope that helps!


How To Get ID From A Clicked Row Of MSFlexGrid?

I made a script to load a query from Access database and put that into the MSFelxGrid.

I managed to get so that with DoubleClick I get the ID of the row 1 but how do I make it so that when I click a certain row I get the ID for THAT clicked row?

    Set RsResults = New ADODB.Recordset
    RsResults.Open "select * from users", dbDatabase, adOpenKeyset, adLockOptimistic
    MSFlexGrid1.Cols = RsResults.Fields.Count
    MSFlexGrid1.Rows = RsResults.RecordCount + 1
    MSFlexGrid1.TextMatrix(0, 0) = "A"
    MSFlexGrid1.TextMatrix(0, 1) = "B"
    MSFlexGrid1.TextMatrix(0, 2) = "C"
    Dim i, j
    With RsResults
        'move to the first record
        i = 1
        Do While i <= .RecordCount
            j = 0
            'this loop now fills up the grid with the field "value"
            Do While j < .Fields.Count
                If Not IsNull(.Fields(j).Value) Then
                    MSFlexGrid1.TextMatrix(i, j) = .Fields(j).Value
                End If
                j = j + 1
            .MoveNext 'move to the next record
            i = i + 1
    End With

    RsResults.Close 'Close the Recordset
    Set RsResults = Nothing 'Clear the recordset from memory

Private Sub MSFlexGrid1_DblClick()
    MsgBox MSFlexGrid1.TextMatrix(1, 0)
End Sub

Edited by - Artur Gajewski on 6/8/2004 4:31:24 AM

Button Gets Clicked Twice
i'm getting a weird problem. I've this ok button and when i click on it the method that i have for it okButton_click is executed twice. Here's the code for it:


public void okButton_Click(object sender, System.EventArgs e)
char[] seps = { ' ' };
String text;
//tokenize to get the code

String[] values = text.Split(seps);

//add to HeadersArray
for (int i=0; i<values.Length; i++)


//add to headersListBox
for (int i=0; i<headersArr.Count; i++)
//populate fileList listbox

and i call it by the following line:

this.okButton.Click+=new System.EventHandler(this.okButton_Click);

this is causing my HeadersList Box to be populated twice. Is there some property that i've to change or what's the problem??

Copy Is Clicked
I need a function or event that is sent when the copy item in the pop up menu is clicked.

Know If Tab Icon Is Clicked
Is it possible to know if the icon of a tab control (common controls) is clicked?

Open When Doubble Clicked
Hi ppl...

I would like my programe to open when any .mp3 file is doubble clicked.. ive searched the forums, looked throught the registry, and have found some things of intrest but i cannot seem to make sence of them so here i am

I know now to do this with an exe file and have looked at


but when i change the value of these (so it points to my app) it still dosn't bring up my prog up.. Im starting to think that it is something else goin on here as well cause at them moment the values of those two are

"C:PROGRA~1WINDOW~1wmplayer.exe" /Open "%L"
"C:PROGRA~1WINDOW~1wmplayer.exe" /Play "%L"

Yet when i doubble click an mp3 it dosn't use the Windows Media player, it uses another player on my computer..

Am i right to change those values or should i be looking somewere else??

Thanks a million

Copyright 2005-08, All rights reserved