Excel VBA 宏:将 Sheet1 数据按照日期填充到 Sheet2 多个表格
这个问题可以通过 VBA 宏来实现。具体步骤如下:
-
在 Excel 中打开工作簿,按下 Alt + F11,打开 VBA 编辑器。
-
在 VBA 编辑器中,选择要编写宏的工作簿,然后新建一个模块。
-
在模块中编写以下代码:
Sub FillData()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim lastRow1 As Long, lastRow2 As Long
Dim i As Long, j As Long
Dim dateValue As Date
Dim isDateFound As Boolean
Set ws1 = ThisWorkbook.Worksheets("Sheet1")
Set ws2 = ThisWorkbook.Worksheets("Sheet2")
lastRow1 = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row
For i = 2 To lastRow1
dateValue = ws1.Cells(i, 1).Value
isDateFound = False
For j = 2 To ws2.Rows.Count Step 10
lastRow2 = ws2.Cells(j, "A").End(xlUp).Row
If lastRow2 < j + 9 Then
If j = 2 Or ws2.Cells(j - 1, "A").Value <> dateValue Then
ws2.Cells(j, "A").Value = dateValue
ws1.Range(ws1.Cells(i, 2), ws1.Cells(i, ws1.Columns.Count)).Copy _
Destination:=ws2.Range(ws2.Cells(j + 1, 2), ws2.Cells(j + 9, ws2.Columns.Count))
isDateFound = True
Exit For
End If
End If
Next j
If Not isDateFound Then
MsgBox "Data for ' & dateValue & ' cannot be added to Sheet2."
End If
Next i
MsgBox "Data filling completed."
End Sub
- 在主窗口中,选择要执行的工作簿,然后按下 F5 运行该宏。
该宏将遍历 Sheet1 中的日期列,并将相应的数据填充到 Sheet2 中的表格中。如果某个日期的数据无法放入任何表格中,则会弹出对话框提示。
原文地址: https://www.cveoy.top/t/topic/lDQw 著作权归作者所有。请勿转载和采集!