0

I'm trying to write a function that merges multiple rows of text in a column into a single cell based on a pre determined count. My goal is to generate a flexible function to aid in compiling / interperting large quantaties of data. The code I've written returns #NAME? and I cant figure out where the error is. My code is as follows:

Function vmrg(countref As Integer, datref As Integer) As String
If IsEmpty(ActiveCell.Offset(0, -countref)) Then % check if cell containing count is blank
vertmerge = "N/A"                                % if blank, state N/A
Else
    Dim datlst(0 To ActiveCell.Offset(0, -countref).Value - 1) As String 
    Dim i As Integer                                                      
    For i = 0 To ActiveCell.Offset(0, -countref).Value - 1  
        datlst(i) = ActiveCell.Offset(i, -datref).Text  %fill array with data
    End
    vertmerge = datlst(0)
    For i = 1 To ActiveCell.Offset(0, -countref).Value - 1  % merge array to a single string
        vertmerge = vertmerge & ", " & datlst(i)
        End
   End
End Function

I have matlab and some C++ experience but this is the first time I've used VBA so my syntax is probably odd in some areas and wrong in others. Ideally I would like to reference the cells where the data and count info are stored, but for now I'm hoping to correct my syntax and set a jumping off point for further development of this function. Any reccomendations are appreciated.

Code Rev_1: I still have an output of #NAME? but I think I've corrected(?) some of the issues

Function vertmerge(countref As Range, datref As Integer) As String
If IsEmpty(countref) = True Then
vertmerge = "NA"
Else
Dim datlst(0 To countref.Value - 1) As String
Dim i As Integer
For i = 0 To countref.Value - 1
datlst(i) = countref.Offset(i, datref).Text
Next i
vertmerge = datlst(0)
For i = 1 To countref.Value - 1
vertmerge = vertmerge & ", " & datlst(i)
Next i
End
End Function
4

1 回答 1

0

你在这里做一些危险的事情!

首先 - 您从函数内部引用“ActiveCell”;但是您不知道函数运行时哪个单元格将处于活动状态!相反,将目标单元格作为参数传递:

=vmrg("B6", 5, 6)

并将您的函数原型更改为

Function vmrg(r as Range, countref as Integer, datref as Integer)

现在你可以参考与 r 相关的东西

r.Offset(1,2)

等等

接下来-您永远不会将任何内容分配给vmrg. 在 VBA 中,函数返回值的方式是 with(在这种情况下)

vmrg = 23

您正在将事物分配给一个名为的变量vertmerge- 但这不是您的函数的名称。至少添加

vmrg = vertmerge

就在回来之前。那可能会做到。如果没有您的电子表格的完整示例,我无法为您提供更多帮助。

于 2013-03-13T21:08:06.193 回答