如何在一个范围内的列的一部分中循环遍历单元格?

时间:2019-01-22 21:53:48

标签: excel vba

我正在尝试在Excel上创建计划时间表。在一张纸中,有一部分E6:W45单元格包含我希望循环通过的数据。本节中的某些单元格已填充,而有些则未填充,我只是在检查它们中是否有东西。

我设法做到这一点来计算完成的“实际”百分比。但是,现在我正在尝试计算完成的“计划”百分比。为此,我需要首先查看范围E4:W4,因为其中的每个单元格都有一个数字,显示它是星期几。然后,对于此范围内小于或等于实际周数的每个单元格,我然后要遍历E6:E45其他范围内相应列中的单元格。

例如如果当前是第10周,则将发生的第一件事是第10周,第11周,第12周...,依此类推,直到第16周为止。然后在另一个范围中,我只想遍历那些首先被计数的列中的单元格。有谁知道我该怎么做,我已经尝试了很多东西,但是它们没有用。

我认为我可能需要根据函数的输出手动创建一个新范围。但是,我不确定如何执行此操作。

Function CalcTarget1(range_data As Range, other_range As Range, weeksOut As Integer)

    Dim cell As Range
    Dim col As Range
    Dim c As Range

    Dim count As Double
    Dim sum As Double
    Dim box As Double

    For Each cell In range_data
        If cell.Style = "Style 1" Then
            count = count + 1
        End If
    Next cell

    If count > 0 Then
        sum = 100 / count
    Else
        sum = 0
    End If

    For Each col In range_data
            If col.Value > weeksOut Then
                For Each c In other_range
                    If c.Style = "Style 1" Then
                          box = box + 1
                     End If
                Next c
        End If
    Next col

    CalcTarget1 = Round(sum, 1) * box & "%"

End Function

此代码无法正常工作,因为它返回0%

谢谢您的时间。

1 个答案:

答案 0 :(得分:2)

根据您的问题,我已了解以下步骤:

  1. 浏览单元格E4至W4并检查单元格值
  2. 如果单元格值小于或等于星期数,则循环遍历该列的6至45行
  3. 用单元格做一些事情(也许算吗?这个步骤在您的问题中尚不清楚。您似乎知道如何计算所需的东西,您只需要知道如何首先执行步骤1和步骤2)< / li>

因此,我写了一个小函数来完成此任务。如果失败,则返回错误描述。只需插入您要计算的内容即可。

Function ColumnLooper(iWeekNum As Long) As Variant
    On Error GoTo errHandler

    'declarations
    Dim iCol As Long, iRow As Long
    Dim myRange As Range

    'initial cell, (top left)
    Set myRange = Range("E4")

    'Check week number
    'by looping through cells E4:W4
    For iCol = 0 To 18
        'Check if the cell value is less than or equal to
        'the week number
        If myRange.Offset(0, iCol).Value <= iWeekNum Then
            'Loop through the corresponding column
            'if the above statement is true (You could
            'also do anything else here)
            For iRow = 2 To 41
                'Do whatever you want here...
                'if you want to reference the specific
                'cell, use myRange.Offset(iRow, iCol)

            Next iRow
        End If
    Next iCol

Exit Function
errHandler:
    'return error
    ColumnLooper = Err.Description
End Function
相关问题