尝试编写一个宏,使用 2 个范围(房价和相应季节)的数据快速填写酒店的每月房价

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

[输入每月数据之前的样子]

[宏正常工作时应该是什么样子]

For seasoncolumn = 30 To 34
    Cells(42, seasoncolumn).Value = season
    
    For rows = 42 To 1300
        For months = 35 To 35 + season
            Cells(rows, months).Value = rate
        Next months
    Next rows
Next seasoncolumn

非常感谢任何帮助或想法!

excel vba loops multidimensional-array nested-loops
1个回答
0
投票

您需要汇总季节计数以匹配月份数。您还需要从您的季节编号中获取匹配的费率编号。

您尚未向我们提供示例工作表,因此我不知道您的数据在工作表上的位置。我在下面的代码中添加了一些常量,您需要更改这些常量才能获取目标单元格。基本处理代码位于这些常量下面:

Dim lastRow As Long
Dim rates() As Variant
Dim seaons() As Variant
Dim months() As Variant
Dim r As Long, m As Long, s As Long, agg As Long

Const HEADER_ROW As Long = 1 'row containing headers.
Const RATES_FIRST_COL As String = "A" 'first column of rates
Const SEASONS_FIRST_COL As String = "F" 'first column of seasons
Const MONTHS_FIRST_COL As String = "K" 'first column of months
Const RATES_AND_SEAONS_COUNT As Long = 5

With Sheet1
    lastRow = Sheet1.Range(RATES_FIRST_COL & .Rows.Count).End(xlUp).Row
    rates = .Range(RATES_FIRST_COL & HEADER_ROW & ":" & RATES_FIRST_COL & lastRow).Resize(, RATES_AND_SEAONS_COUNT).Value
    seaons = .Range(SEASONS_FIRST_COL & HEADER_ROW & ":" & SEASONS_FIRST_COL & lastRow).Resize(, RATES_AND_SEAONS_COUNT).Value
    months = .Range(MONTHS_FIRST_COL & HEADER_ROW & ":" & MONTHS_FIRST_COL & lastRow).Resize(, 12).Value
End With

For r = 2 To UBound(rates, 1) ' start from 2 as 1 contains the headers
    s = 1
    agg = seaons(r, s)
    For m = 1 To 12
        If m > agg Then
            s = s + 1
            agg = agg + seaons(r, s)
        End If
    months(r, m) = rates(r, s)
    Next
Next

With Sheet1
    .Range(MONTHS_FIRST_COL & HEADER_ROW & ":" & MONTHS_FIRST_COL & lastRow).Resize(, 12).Value = months
End With
© www.soinside.com 2019 - 2024. All rights reserved.