Forum Discussion

PMHunt1955's avatar
PMHunt1955
Brass Contributor
Nov 22, 2019
Solved

Passing a workbook name and worksheet number to find out worksheet's name

I am wanting to find out the worksheet name for a worksheet in another workbook. I seem to be close but all I am always getting is a #VALUE# error. I think it may be in the call but it could be in t...
  • Subodh_Tiwari_sktneer's avatar
    Subodh_Tiwari_sktneer
    Nov 23, 2019

    PMHunt1955 

    Sorry I misunderstood. I thought you were calling the function within the module itself.

     

    You may tweak your function like this and let me know if that works for you...

     

     

    Function Sheet_Name_from_Sheet_Num(ByVal Workbook_Source As String, ByVal Worksheet_Number As Long) As String
    
    Dim wbSource As Workbook
    Dim wsSource As Worksheet
    
    If IsWorkbookOpened(Workbook_Source) Then
        Set wbSource = Workbooks(Workbook_Source)
    Else
        Sheet_Name_from_Sheet_Num = "Workbook is not opened!"
        Exit Function
    End If
    
    If SheetExists(wbSource, Worksheet_Number) Then
        Set wsSource = wbSource.Worksheets(Worksheet_Number)
    Else
        Sheet_Name_from_Sheet_Num = "Worksheet with Index " & Worksheet_Number & " was not found!"
        Exit Function
    End If
    
    Sheet_Name_from_Sheet_Num = wsSource.Name
    
    End Function
    
    Function IsWorkbookOpened(ByVal wbName As String) As Boolean
    Dim wb As Workbook
    
    On Error Resume Next
    Set wb = Workbooks(wbName)
    On Error GoTo 0
    
    If Not wb Is Nothing Then IsWorkbookOpened = True
    End Function
    
    Function SheetExists(wb As Workbook, ByVal wsIndex As Long) As Boolean
    Dim ws As Worksheet
    
    On Error Resume Next
    Set ws = wb.Worksheets(wsIndex)
    On Error GoTo 0
    If Not ws Is Nothing Then SheetExists = True
    End Function

     

     

    And then you may call this function on the worksheet like this...

     

    =Sheet_Name_from_Sheet_Num("Johnson_Project_Patriarchal_Lines.xlsm",A2)