Friday, December 25, 2015

How To get worksheet Name in VBA

How to get worksheet name in VBA


1
2
3
4
5
6
7
8
9
Sub Sample1()
    Dim ws As Worksheet, tmp As String
    For Each ws In Worksheets
        If ws.Name <> "" Then
            tmp = tmp & ws.Name & vbCrLf
        End If
    Next ws
    MsgBox tmp
End Sub


Below code, get worksheet name with count the sum of sheet first.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Sub Sample2()
    Dim ws As Worksheet, tmp As String
    Dim n As Integer, i As Integer
    
    n = ActiveWorkbook.Worksheets.Count ' there are 5 sheets
    
    For i = 1 To n
        tmp = tmp & Sheets(i).Name & vbCrLf
    Next i
    MsgBox tmp
End Sub

Below code, just get second sheet name


1
2
3
4
5
6
7
Sub Sample3()
    Dim tmp As String
    
    tmp = Sheets(2).Name 'just get second sheet name
    
    MsgBox tmp
End Sub

Download File



No comments :

Post a Comment