VBA 循环访问单元格的函数

VBA function to iterate through cells

我正在为 Excel 开发一个 VBA 函数。它将接受一个整数(我们称之为 ref_num)和一个范围的输入参数。它将搜索范围,寻找 ref_num 作为单元格的值。当它找到 ref_num(可能存在也可能不存在)时,它将转到 ref_num 所在列的第二行,并将该值作为字符串存储在 return 变量(值为日期,1-31各有自己的一列)。每次在列中找到 ref_num 时,第二行中的值将附加到 return 字符串。

稍微具体一点的例子: ref_num为2,2出现在A、B、C列,A2、B2、C2中的值分别为1、2、3,所以函数必须return"1 , 2, 3".

这是我的伪代码,但我需要一些帮助来填补空白... 请注意,这目前不起作用,并且该算法非常暴力。我只是想让一些东西工作。

Function GetDays(ref_num As Integer, range_o_cells As Range) As String
    Dim num_dates As Integer
    Dim day As String
    Set num_dates = 0

    'iterate through all the cells and see if the value is ref_num
    For Each c In range_o_cells

        If c.Value = ref_num Then
            'get the cell's column, then reference the second row and get the value. Note that this will be an int that we need to convert to a string
            'I seriously doubt the following line will work
            day = CStr(Cells(c.Column, 2).Value)

            'Once you have the value, append it to the return value
            If num_dates = 0 Then
                'This is the first value we've found, so we don't need to prepend a comma
                GetDays = day
                num_dates = 1
            Else
                'This is probably not valid VBA syntax...
                GetDays = GetDays & ", " & day
         End If

    Next c
End Function

请注意,目前,如果我这样称呼它:=GetDays(AG39, $P:$W0) 其中 AG39 是包含 ref_num 的单元格,我得到 #NUM!

您的代码中存在多个问题

  1. 您不使用 Set 表示整数
  2. 缺少 End If
  3. 如您所料,您对 Cells 的索引是不确定的
  4. 您应该将 return 字符串构建到 day 中并将其分配给一个地方的函数
  5. 在范围内循环很慢
  6. 你应该声明所有个变量

更好的方法是将数据移动到变体数组,然后循环它。还包括传递给 range_o_cells 范围内的 header 数据(我猜那是 $P:$W0

这是重构后的代码

Function GetDays( _
  ref_num As Long, _
  range_o_cells As Range, _
  Optional Sep As String = ", ") As String

    Dim dat As Variant
    Dim rw As Long, col As Long
    Dim day As String

    dat = range_o_cells.Value

    For col = 1 To UBound(dat, 2)
    For rw = 3 To UBound(dat, 1)
        If dat(rw, col) = ref_num Then
            day = day & dat(2, col) & Sep
        End If
    Next rw, col
    If Len(day) > 0 Then day = Left$(day, Len(day) - Len(Sep))
    GetDays = day
End Function