VBA函数迭代细胞

时间:2015-01-19 05:22:40

标签: excel vba

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

稍微更具体的例子: ref_num为2,并且在A,B和C列中出现2 .A2,B2和C2中的值分别为1,2和3,因此该函数必须返回" 1,2,3&# 34。

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

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$3:$W$500)其中AG39是包含ref_num的单元格,我得到#NUM!

1 个答案:

答案 0 :(得分:1)

您的代码中存在多个问题

  1. 您不使用Set作为整数
  2. 缺少End If
  3. 如您所疑,您对Cells的索引是iffy
  4. 您应该将返回字符串构建到day并将其分配到函数中
  5. 在一个范围内循环很慢
  6. 您应该声明所有变量
  7. 更好的方法是将数据移动到变量数组,然后循环。还包括传递给range_o_cells的范围中的标题数据(我猜那是$P$1:$W$500

    这是您重构的代码

    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