如何将单元格的值用作先前已存储的变量

时间:2018-12-24 02:35:12

标签: excel vba excel-vba

这是我的问题:

我有一个单元格,即I1,其属性值等于Monday

以前,我已将Monday=存储为一个范围的总和。

我需要引用单元格I1并获取总和,以便将结果与if语句进行比较。

如果Cells(2, i).Offset(-1, 0).Value < 2 Then,则需要根据一周中每一天的限制,将宏填充为一定数量的“ 1”,

Sub dayweek()

    Dim i As Byte, Monday As Byte, Tuesday As Byte, Wednesday As Byte, Thursday As Byte, Friday As Byte
    i = 9

    Monday = Application.WorksheetFunction.Sum(Range(Cells(2, i), Cells(2, i + 4)))

    Tuesday = Application.WorksheetFunction.Sum(Range(Cells(2, i - 1), Cells(2, i + 3)))

    Wednesday = Application.WorksheetFunction.Sum(Range(Cells(2, i - 2), Cells(2, i + 2)))

    Thursday = Application.WorksheetFunction.Sum(Range(Cells(2, i - 3), Cells(2, i + 1)))

    Friday = Application.WorksheetFunction.Sum(Range(Cells(2, i - 4), Cells(2, i)))

    Do While i < 14
        If Cells(2, i).Offset(-1, 0).Value < 2 Then 'In this cell i have the value "monday","tuesday", etc...

            Cells(2, i).Value = 1
            i = i + 1
        Else
            Cells(2, i).Value = 0
            i = i + 1
        End If
    Loop

End Sub

2 个答案:

答案 0 :(得分:0)

我认为选择方案是命名每天的范围,然后取其总和。

python manage.py collectstatic

答案 1 :(得分:0)

在我的评论之后,我建议您简单地使用一个数组来存储总和结果,然后将其写入所需的单元格中:

Sub dayweek()
    Dim startColumn As Long, nColumns As Long, jCol As Long

    startColumn = 9
    nColumns = 5

    ReDim results(0 To nColumns - 1) As Long ' array storing the results

    For jCol = 0 To nColumns - 1
        results(jCol) = IIf(Application.WorksheetFunction.Sum(Cells(2, startColumn - jCol).Resize(, nColumns)) < 2, 1, 0)
    Next
    Cells(2, startColumn).Resize(, nColumns).Value = results
End Sub