循环遍历列并创建工作表,错误1004

时间:2015-04-24 14:42:34

标签: excel vba excel-vba

我有一个原始文件“Categories_by_Year.xlsm”,其中我在2010年和2014年之间每年都有包含不同类别和数据的表格(每列一个类别)。我想要的是每年创建一个新工作簿,并将每个类别保存为文件中的新工作表。每列的第一行是类别名称,用于新工作表的名称。从第2行到最后一个非空行 - 数据被复制,然后在新工作表中转置。

当我运行以下代码时,将创建文件和第一张表(第一列被复制并转置到新文件中)。但是,之后我得到了运行时错误'1004'。我尝试从不同的列开始,但在创建第一个列之后仍然会出现错误。

Sub NewShForEachCategory()
Dim LastRow As Double

For year = 2010 To 2014

      Workbooks.Add
      ActiveWorkbook.SaveAs Filename:="C:\" & CStr(year) & ".xls", FileFormat:=xlExcel8

      Workbooks("Categories_by_Year.xlsm").Activate

For col = 1 To 35

  If Not IsEmpty(Workbooks("Categories_by_Year.xlsm").Worksheets(CStr(year)).Cells(1, col)) Then

  Category = Workbooks("Categories_by_Year.xlsm").Worksheets(CStr(year)).Cells(1, col).Value
  LastRow = Workbooks("Categories_by_Year.xlsm").Worksheets(CStr(year)).Cells(Rows.Count, col).End(xlUp).Row

   Workbooks("Categories_by_Year.xlsm").Worksheets(CStr(year)).Range(Cells(2, col), Cells(LastRow, col)).Copy
   Workbooks(CStr(year) & ".xls").Activate
   Workbooks(CStr(year) & ".xls").Worksheets.Add.Name = Category
   Workbooks(CStr(year) & ".xls").Worksheets(Category).Cells(1, 1).PasteSpecial Transpose:=True
  End If

Next col

Next year

End Sub

1 个答案:

答案 0 :(得分:0)

未测试:

Sub NewShForEachCategory()

Dim wbCBY as Workbook, wbY as Workbook, Category
Dim sht as Worksheet, year as Long, col as Long

    Set wbCBY = Workbooks("Categories_by_Year.xlsm")

    For year = 2010 To 2014

         Set wbY = Workbooks.Add()
         wbY.SaveAs Filename:="C:\" & CStr(year) & ".xls", _
                   FileFormat:=xlExcel8

         Set sht = wbCBY.Worksheets(CStr(year))

         For col = 1 To 35

            Category = Trim(sht.Cells(1, col).Value)

            If Len(Category) > 0 Then

              sht.Range(sht.Cells(2, col), _
                        sht.Cells(sht.Rows.Count, col).End(xlUp)).Copy

              With wbY.Worksheets.Add()
                 .Name = Category
                 .Cells(1, 1).PasteSpecial Transpose:=True
              End With

            End If

        Next col

    Next year

End Sub