将工作表复制到新工作簿并将工作表的名称更改为撰写名称

时间:2017-10-17 21:09:46

标签: excel vba excel-vba

我将很多工作簿复制到1个工作簿,但由于不同工作簿上的所有工作表都具有相同的名称,并且每个工作簿都在B1上具有该文件的名称,因此我想将其命名为表格为"违规(姓名)"

这是我对该部分的代码

Dim wc As Worksheet
Dim ws As Worksheet
Dim SheetNewName As String
Dim Parname As String
Dim SheetName As String

Select Case wc.Cells(n, 1)
    Case "PK"
        SheetName = "Peak"
    Case "Sfactor"
        SheetName = "SF Supply"
    Case Else
        SheetName = wc.Cells(n, 1)
End Select

Set ws = ThisWorkbook.Sheets("Sheet1")
Set wc = ActiveWorkbook.Sheets("Violations Summary")
Set Parname = wc.Range("B1")
Set SheetNewName = SheetName & "(" & Parname & ")"

ActiveWorkbook.Sheets(SheetName).Copy After:=ThisWorkbook.Sheets(1)
Set lastsheet = ThisWorkbook.Sheets(ThisWorkbook.Sheets.count).Select
lastsheet.Name = SheetNewName

尝试更改新工作簿上新工作表的名称时收到错误,错误是

  

运行时错误' 13':类型不匹配

在这一行

Set SheetNewName = SheetName & "(" & Parname & ")"

但是如果我修改代码就像这些

Set Parname = wc.Range("B1")
Set SheetNewName = SheetName & "(" & Parname & ")"

ActiveWorkbook.Sheets(SheetName).Copy After:=ThisWorkbook.Sheets(1)
Set lastsheet = ThisWorkbook.Sheets(1).Select
lastsheet.Name = Parname

复制工作表,但不会更改名称并收到错误

  

运行时错误' 1004':   应用程序定义或对象定义的错误

1 个答案:

答案 0 :(得分:1)

您不能"SET"作为字符串变量:

Set SheetNewName = SheetName & "(" & Parname & ")"

需要修改为

SheetNewName = SheetName & "(" & Parname & ")"

Set Parname = wc.Range("B1")

需要

Parname = wc.Range("B1")