我正在尝试将工作簿名称Source.xlsm的sheet1复制到工作簿名称s.xlsx。然后将复制的工作表重命名为列值D1。 我的代码正确地复制了工作表,但在重命名时它给出了错误。
而不是显示已经退出的消息名称,它将转移到其他部分并给出错误:运行时错误' 1004':无法将工作表重命名为另一个工作表的名称。这一行Sheet.Name = range(" D1")突出显示。
请纠正我的错误。
我的代码是:
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
答案 0 :(得分:1)
更改了已解决的代码和问题。以下是供参考的代码:
Sub movesheet3()
Dim name As String
Dim sPath As String
Dim wbPath1 As Workbook
name = Workbooks("Source.xlsm").Sheets("Sheet1").range("D1").value
sPath = Application.ActiveWorkbook.Path & "\s\s.xlsx"
Set wbPath1 = Workbooks.Open(sPath)
wbPath1.Activate
'Workbooks("Source.xlsm").Sheets("Sheet1").Copy After:=wbPath1.Sheets(Sheets.Count)
For i = 1 To (Worksheets.Count)
If ActiveWorkbook.Sheets(i).name = name Then
MsgBox "Sheet name already exist. GO back to the sheet and enter valid name in D1 cell"
Exit Sub
End If
Next
Workbooks("Source.xlsm").Sheets("Sheet1").Copy After:=wbPath1.Sheets(Sheets.Count)
Sheets(ActiveSheet.name).name = name
ActiveWorkbook.Close True
End Sub
感谢大家的帮助....干杯