VBA函数遍历单元格

我正在开发Excel的VBA函数。 它将采用一个整数的input参数(我们称之为ref_num)和一个范围。 它将search范围,寻找ref_num作为一个单元格的值。 当它findref_num(可能存在也可能不存在)时,它将进入ref_num所在列的第二行,并将该值作为string存储在返回variables中(值为date, 31个都有自己的专栏)。 每当在列中findref_num时,第二行中的值将被附加到返回string。

稍微更具体的例子:ref_num是2,在列A,B和C中出现2,A2,B2和C2中的值分别是1,2和3,所以函数必须返回“1,2, 3" 。

这是我的伪代码,但我需要一些帮助填补空白…请注意,目前这是行不通的,而且algorithm是非常蛮力。 我只想得到一些工作。

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. 你不要使用Set来整数
  2. 缺less一个End If
  3. 正如你怀疑的,你的索引到Cells是iffy
  4. 你应该build立你的返回string到day并将其分配给一个地方的function
  5. 循环范围很慢
  6. 你应该声明所有的variables

更好的方法是将数据移动到一个变体数组,然后循环。 还包括传递给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