[英]Looping through columns and creating worksheets, error 1004
I have an original file "Categories_by_Year.xlsm" where I have sheets for each year between 2010 and 2014 containing different categories and data (one category per column). 我有一个原始文件“ Categories_by_Year.xlsm”,其中有2010年至2014年之间每年的工作表,其中包含不同的类别和数据(每列一个类别)。 What I want is for each year a new workbook to be created and than each category to be saved as a new worksheet in the file.
我想要的是每年创建一个新的工作簿,而不是将每个类别另存为文件中的新工作表。 The first row of each column is the category name, which is used for the new worksheets' names.
每一列的第一行是类别名称,该类别名称用于新工作表的名称。 From row 2 to the last not empty row - the data is copied and then transposed in the new worksheet.
从第2行到最后一个非空行-复制数据,然后将其转置到新工作表中。
When I run the following code, the file and the first sheet is created (the first column is copied and transposed in the new file). 当我运行以下代码时,文件和第一张纸被创建(第一列被复制并转置到新文件中)。 However, after that i got run-time error '1004'.
但是,在那之后,我得到了运行时错误“ 1004”。 I tried starting with different columns and it still trows an error after creating the first one.
我尝试从不同的列开始,但在创建第一个列之后仍然引发错误。
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
Untested: 未经测试:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.