简体   繁体   中英

How to display the sum of selected cells as a tip? Excel VBA

This is a question that many might not find it is necessary but to me it is very helpful as I have a problem of distraction.

Excel can display the sum of the selected cell in the top left corner 在此处输入图片说明

But is there anyway to make it appear next to the mouse pointer?

This could be a solution, although it isn't perfect by any means, but you have to be careful if you want to use data validation elsewhere in the worksheet as it will break that.

This would need work on resetting the data validation range when you select a different range, but you should be able to determine if this approach is of any use first.

In the selection change event

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
 doSumTip
End Sub

and then use data validation to set an input message on your selection. You can alter this to show counts or averages etc.

Sub doSumTip()
Dim myRng As Range
Dim sumTip
Set myRng = Selection
    If myRng.Count > 1 Then
       sumTip = WorksheetFunction.Sum(myRng)
        With Selection.Validation
            .Delete
            .Add Type:=xlValidateInputOnly
            .IgnoreBlank = True
            .InputMessage = sumTip
        End With
    Else
        With Selection.Validation
            .Delete
            .Add Type:=xlValidateInputOnly
            .InputMessage = ""
        End With
    End If
 Set myRng = Nothing
End Sub

OR you could create your own tooltip with a textbox using the selection range and positioning it based on that selection, suggest the textbox be colored and flat like the data validation one

Sub doSumTip()
Dim myRng As Range
Dim sumTip
Set myRng = Selection
    If myRng.Count > 1 Then
       sumTip = WorksheetFunction.Sum(myRng)
       cTop = myRng.Top
       cWidth = myRng.Left + myRng.Width
       ActiveSheet.TextBox1.Left = cWidth
       ActiveSheet.TextBox1.Top = cTop
       ActiveSheet.TextBox1.Text = sumTip
       ActiveSheet.TextBox1.Visible = True

     Else
       ActiveSheet.TextBox1.Visible = False
     End If
 Set myRng = Nothing
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM