Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch multiple selected sheets handles in a workbook using Excel VBA API

Tags:

excel

vba

There is a way to select multiple Excel sheets and then do some action on them like Print. However given a workbook, how do i get to know which sheets are selected. There is a vba property Application->ActiveSheet which gives us current active sheet, but i couldn't find any way to get multiple sheets for this.

like image 929
hjindal Avatar asked Jan 10 '12 10:01

hjindal


1 Answers

Is this what you want?

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim SelectedSheets() As String
    Dim n As Long, i As Long

    n = 0
    For Each ws In ActiveWindow.SelectedSheets
        ReDim Preserve SelectedSheets(n)
        SelectedSheets(n) = ws.Name
        n = n + 1
    Next

    For i = LBound(SelectedSheets) To UBound(SelectedSheets)
        '~~> This will give you the list of selected sheets
        Debug.Print SelectedSheets(i)        
    Next i

    '~~> The collection can also be used as below
    'Sheets(SelectedSheets).Copy
    'Sheets(SelectedSheets).Select   ' e.g., to re-select them later
End Sub
like image 175
Siddharth Rout Avatar answered Oct 09 '22 11:10

Siddharth Rout