Home » excel » excel – VBA Add-In – Count selected cells

excel – VBA Add-In – Count selected cells

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have an existing add-in which has other functions to apply to many excel files. I would like to perform this action where I select x numbers of cell and if it exceeds 100 counts then it will prompt the user a message. This action should work at any workbook that I am going to open (and import the add-in into the workbook). I have looked at some links about application events but I still do not understand how it should work for me. I would appreciate if anyone could help me with this.

I have referenced the following codes from

1 – https://superuser.com/questions/920578/count-number-of-selected-cells

2 – http://www.excely.com/excel-vba/using-message-box.shtml

Codes:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim totalCells As Long
totalCells = ActiveSheet.Selection.Cells.Count

If totalCells > 100 Then
    MsgBox (totalCells)
End If

End Sub
How to&Answers:

OK, I copied Chip Pearson’s example, and added this code to ThisWorkbook of my addin, seems to work OK. See if it works for you.

Private WithEvents App As Application

Private Sub App_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
  Dim totalCells As Long
  totalCells = Target.Cells.Count
  If totalCells > 100 Then MsgBox totalCells
End Sub

Private Sub Workbook_Open()
  Set App = Application
End Sub