I am trying to copy sheet1 of workbook name Source.xlsm to workbook name s.xlsx. And then rename the copied sheet to a column value say D1. My code copies the sheet properly but while renaming it is giving error.
Instead of displaying message name already exits it is going to else part and giving error: Run-time error '1004': Can not rename a sheet to name as of another sheet. And this line Sheet.Name = range("D1") is highlighted.
Plese correct me what i am doing wrong.
My Code is:
Sub savesheet()
Dim sPath As String
Dim wbPath1 As Workbook
Dim wsName As String
sPath = Application.ActiveWorkbook.Path & "\s\s.xlsx"
Set wbPath1 = Workbooks.Open(sPath)
Workbooks("Source.xlsm").Sheets("Sheet1").Copy After:=wbPath1.Sheets(1)
'For Each Sheet In ActiveWorkbook.Sheets
For Each Sheet In Workbooks("s.xlsx").Sheets
If Sheet.Name = range("D1") Then
MsgBox "name already exits"
Exit Sub
Else
Sheet.Name = range("D1")
End If
Next
End Sub
range("D1")
is not the range("D1") on each worksheet. Provide proper parent worksheet reference as you loop through the worksheets in wbPath1. – user4039065range("D1")
torange("D1").value
. It is even better to trace the error by assigning this range to a variable you have already decalerd:wsName = range("D1").value
. And be sure you are referencing to the right workbook and sheet. So an extended code would be:wsName = Workbooks("Source.xlsm").sheets(1).range("D1").value
– Andrey Ampilogov