我正在尝试使用“with”语句从书中的所有其他工作表创建一个包含数据(sheet1)的常用工作表。但是它出现了1004错误。怎么解决?
Dim Sh As Worksheet
Dim c As Long
Dim lRow As Integer
c = 1
For Each Sh In ThisWorkbook.Worksheets
If Sh.Name <> "Sheet1" Then
With Sheets("Sheet1")
lRow = Sheets(Sh.Name).Cells(Rows.Count, 1).End(xlUp).Row + 1
.Range(Cells(1, c), Cells(lRow, c + 4)) = Sh.Range(Cells(1, 1), Cells(lRow, 5))
End With
c = c + 4
End If
Next
End Sub
答案 0 :(得分:1)
您必须使用正确的Cells
对象
worksheet
此外,您可能希望将With Sheets("Sheet1")
放在循环之外,因为它内部没有变化
Option Explicit
Sub main()
Dim Sh As Worksheet
Dim c As Long
Dim lRow As Integer
c = 1
With Sheets("Sheet1")
For Each Sh In ThisWorkbook.Worksheets
If Sh.name <> "Sheet1" Then
lRow = Sheets(Sh.name).Cells(Rows.count, 1).End(xlUp).row + 1
.Range(.Cells(1, c), .Cells(lRow, c + 4)) = Sh.Range(Sh.Cells(1, 1), Sh.Cells(lRow, 5))
c = c + 4
End If
Next
End With
End Sub