我几乎没有编码方面的经验,并且一直在youtube上观看视频以尝试编写一些代码。我有一个包含大量数据的“主”表,我需要获取该数据并将其根据日期传输到每个连续的表中。因此,从nov 17到工作表3的所有数据以及从nov 18到工作表4的所有数据,依此类推。我遇到的问题是当我尝试循环到下一个日期时。
Option Explicit
Sub Copypaste()
'Sets a as variable for number of rows from master sheet
a = Worksheets("Master").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To a 'Loops from i=2 to end
k = 3 'sheet number
J = 43048 'date
If Worksheets("Master").Cells(i, 1).Value = J Then
Worksheets("Master").Rows(i).Copy
Worksheets(k).Activate
'counts rows in sheet pasting to
b = Worksheets(k).Cells(Rows.Count, 1).End(xlUp).Row
'pasts to next blank row
Worksheets(k).Cells(b + 1, 1).Select
ActiveSheet.Paste
Worksheets("Master").Activate
Else
k = k + 1
J = J + 1
End If
Next
End Sub
答案 0 :(得分:0)
您必须将日期置于循环之外,然后再递增一。
Sub Copypaste()
'Sets a as variable for number of rows from master sheet
a = Worksheets("Master").Cells(Rows.Count, 1).End(xlUp).Row
J = 43048 'date
For i = 2 To a 'Loops from i=2 to end
k = 3 'sheet number
If Worksheets("Master").Cells(i, 1).Value = J Then
Worksheets("Master").Rows(i).Copy
Worksheets(k).Activate
'counts rows in sheet pasting to
b = Worksheets(k).Cells(Rows.Count, 1).End(xlUp).Row
'pasts to next blank row
Worksheets(k).Cells(b + 1, 1).Select
ActiveSheet.Paste
Worksheets("Master").Activate
Else
k = k + 1
J = J + 1
End If
Next
End Sub
因此上面的代码应该起作用。如果您尝试将工作表声明为变量,并避免使用Select
和Activate
,则代码会更快-How to avoid using Select in Excel VBA
因此,它看起来像这样:
Sub Copypaste()
a = Worksheets("Master").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To a
k = 3
J = 43048
With Worksheets("Master")
If .Cells(i, 1) = J Then
.Rows(i).Copy
b = Worksheets(k).Cells(Rows.Count, 1).End(xlUp).Row
Worksheets(k).Cells(b + 1, 1).Paste
Else
k = k + 1
J = J + 1
End If
End With
Next
End Sub
第三步,您可以考虑编写普通的变量名。例如。而不是a
写rowsCountMaster
,而不是J
写currentDate
。