Hi, I have some code that sets named ranges based on sheet names defined by the user.
Issue is, sheet names allow characters that range names do no (i.e. #, - etc).
Is there a relatively simple way to clean a sheet name to allow it to be used as a range name.
Code example below. I am using Replace, but unsure how many characters are invalid. Unfortunately I am referencing a third party workbook, so no control over sheet names.
Thanks.
Sub test()
Dim sh As Worksheet, shnm As String, wb As Workbook
Set wb = ThisWorkbook
For Each nm In wb.Names
nm.Delete
Next
For Each sh In wb.Sheets
If sh.Visible = xlSheetHidden Then GoTo continue:
shnm = Replace(Mid(sh.Name, 1, InStr(1, sh.Name, "(") - 2), "#", "_")
For Each col In sh.Range(Cells(2, 2).Address, Cells(2, sh.Range("A2").End(xlToRight).Column).Address).Columns
trw = Cells(2, col.Column).End(xlDown).Row
brw = Cells(trw, col.Column).End(xlDown).Row
coln = col.Column
rAdr = Range(Cells(trw, coln), Cells(brw, coln)).Address
test = col.Value
wb.Names.Add Name:=shnm & Replace(Replace(Replace(col.Value, " ", "_"), "-", "_"), "/", "_"), RefersTo:=rAdr
Next
continue:
Next
End Sub
Issue is, sheet names allow characters that range names do no (i.e. #, - etc).
Is there a relatively simple way to clean a sheet name to allow it to be used as a range name.
Code example below. I am using Replace, but unsure how many characters are invalid. Unfortunately I am referencing a third party workbook, so no control over sheet names.
Thanks.
Sub test()
Dim sh As Worksheet, shnm As String, wb As Workbook
Set wb = ThisWorkbook
For Each nm In wb.Names
nm.Delete
Next
For Each sh In wb.Sheets
If sh.Visible = xlSheetHidden Then GoTo continue:
shnm = Replace(Mid(sh.Name, 1, InStr(1, sh.Name, "(") - 2), "#", "_")
For Each col In sh.Range(Cells(2, 2).Address, Cells(2, sh.Range("A2").End(xlToRight).Column).Address).Columns
trw = Cells(2, col.Column).End(xlDown).Row
brw = Cells(trw, col.Column).End(xlDown).Row
coln = col.Column
rAdr = Range(Cells(trw, coln), Cells(brw, coln)).Address
test = col.Value
wb.Names.Add Name:=shnm & Replace(Replace(Replace(col.Value, " ", "_"), "-", "_"), "/", "_"), RefersTo:=rAdr
Next
continue:
Next
End Sub