如何编写一个 VBA 脚本来帮助我在更改 2 个单元格中的输入后将工作表上的数据附加到另一个工作表?

问题描述 投票:0回答:1

我的工作表现在根据日期(输入到单元格 $B$1 中)和周期(输入到单元格 $D$1 中)更改派生公式,它使用索引匹配从原始数据表中获取计算所需的数据。

我希望将2023年1月1日至2023年12月31日期间每一天的H7:L47中的导出数据附加到另一张表中,其中一天由48个周期组成。是否有可能在Excel中提出一个for循环来做到这一点?

我尝试编写一个脚本,但我不确定如何引用将在 for 循环中更改的两个单元格。我需要一个嵌套循环

适用于 1 月 1 日:12 月 31 日的日期 1:48 时段 将数据附加到新工作表

如果在每个附加的顶部,日期和期间可以包含在该行的前 2 个单元格中,那就太好了

现在一些基本代码:

Sub CalculatePrices()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim startDate As Date, endDate As Date
Dim currentDate As Date
Dim period As Integer
Dim destRow As Integer
 
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
 
startDate = DateSerial(2023, 1, 1)
endDate = DateSerial(2023, 12, 31)

For currentDate = startDate To endDate
    ' Loop through each period
    For period = 1 To 80

不确定如何设置 $B$1 = 当前日期和 $D$1 = 当前期间 并将 H7:L47 中的数据附加到表 3

excel vba input
1个回答
0
投票

微软文档:

Range.Offset 属性 (Excel)

Range.Resize 属性 (Excel)

Option Explicit

Sub CalculatePrices()
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Dim startDate As Date, endDate As Date
    Dim currentDate As Date
    Dim period As Long
    Dim destRow As Long
    Const TAB_RNG = "H7:L47"
    Set ws1 = ThisWorkbook.Sheets("Sheet1")
    Set ws2 = ThisWorkbook.Sheets("Sheet2")
    startDate = DateSerial(2023, 1, 1)
    endDate = DateSerial(2023, 1, 3) ' DateSerial(2023, 12, 31)  **for testing
    Dim RowCnt As Long, ColCnt As Long, srcRng As Range, oCell As Range
    Set srcRng = ws1.Range(TAB_RNG)
    RowCnt = srcRng.Rows.Count
    ColCnt = srcRng.Columns.Count
    For currentDate = startDate To endDate
        ' Loop through each period
        For period = 1 To 3 ' 80  **for testing
            ' update date and period on Sheet1
            ws1.Range("B1").Value = currentDate
            ws1.Range("D1").Value = period
            ' get the first blank cell on Sheet2 Col A
            Set oCell = ws2.Cells(ws2.Rows.Count, 1).End(xlUp).Offset(1)
            ' write date and period
            oCell.Resize(RowCnt).Value = currentDate
            oCell.Offset(, 1).Resize(RowCnt).Value = period
            ' copy table
            oCell.Offset(, 2).Resize(RowCnt, ColCnt).Value = srcRng.Value
        Next
    Next
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.