I'm having a hard time with VBA errors on Excel, can someone help me understanding what this error means?
"VBA Object variable or With block variable not set error"
My function is supposed to check if a sheet exists, if not create the new sheet, rename it and return to the main function. The code works, but the error is always thrown..
Function GetWorksheetFromName(Name As String) As Worksheet
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
If StrComp(WS.Name, Name, vbTextCompare) = 0 Then
Set GetWorksheetFromName = WS
Exit Function
End If
Next WS
With ThisWorkbook
Set WS = Worksheets.Add(After:=Sheets(.Sheets.Count))
WS.Name = Name
End With
Set GetWorksheetFromName = WS
End Function
P.S.: this might help, but I still haven't fixed my code
With GetWorksheetFromName("ABC") : .Range("A1") = 123 : End With. First pass it creates the new worksheet, second pass it uses the same worksheet.