所以我对VBA很新,基本上是为我的第一份工作学习它。
我从Sheet3中的过滤数据透视表中获取数据。这个数据每月更新一次,我需要将这些动态数据(数据结束时的标题和空格除外)复制到下一个可用行中的新工作表(sheet8),因为其他数据也将从其他数据透视表复制到其中。
到目前为止我尝试过的是
Sub Aggregate_Data()
'
' Aggregate_Data Macro
'
Sheet3.Activate
LR = Sheet3.Cells(Rows.Count, 1).End(xlUp).Row
For i = 3 To LR
If Sheet3.Cells(i, 1).Value <> "0" Then
Sheet3.Rows(i).Copy
Sheet8.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).EntireRow.Select
Selection.PasteSpecial xlPasteValues
End If
Next i
End Sub
我不知道我在做什么,很抱歉,如果这段代码毫无意义。但基本上我不断收到运行时错误&#34; 1004&#34;
答案 0 :(得分:0)
假设您在Sheet8.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).EntireRow.Select
这一行上发生了错误,那是因为尝试Select
工作表上的某个范围无效。
除非您需要,否则请避免使用Select
(和Activate
)。 (有关详细信息,请参阅How to avoid using Select in Excel VBA macros。)
我相信你的代码可以改写为:
Sub Aggregate_Data()
'
' Aggregate_Data Macro
'
Dim i As Long
Dim LR As Long
Dim j As Long
Dim c As Long
'Find last used row in Sheet3
LR = Sheet3.Cells(Sheet3.Rows.Count, 1).End(xlUp).Row
'Find last used row in Sheet8
j = Sheet8.Cells(Sheet8.Rows.Count, 1).End(xlUp).Row
'Loop through rows on Sheet3
For i = 3 To LR
'Decide whether to copy the row or not
If Sheet3.Cells(i, 1).Value <> "0" Then
'Update pointer to the next unused row in Sheet8
j = j + 1
'Only copy used columns, to stop it thinking every cell in the
'destination row is "used"
c = Sheet3.Cells(i, Sheet3.Columns.Count).End(xlToLeft).Column
'Copy the values (without using Copy/Paste via the clipboard)
Sheet8.Rows(j).Resize(1, c).Value = Sheet3.Rows(i).Resize(1, c).Value
End If
Next i
End Sub
答案 1 :(得分:0)
使用Variant很简单。
Dim vDB, vR()
Dim n As Long, i As Long, j As Integer, c As Integer
vDB = Sheet3.Range("a1").CurrentRegion
c = UBound(vDB, 2)
For i = 1 To UBound(vDB, 1)
If vDB(i, 1) <> 0 Then
n = n + 1
ReDim Preserve vR(1 To c, 1 To n)
For j = 1 To UBound(vDB, 2)
vR(j, n) = vDB(i, j)
Next j
End If
Next i
Sheet8.Range("a1").Resize(n, c) = WorksheetFunction.Transpose(vR)