Excel VBA用户定义函数仅处理工作簿中的一个工作表

Excel VBA用户定义函数仅处理工作簿中的一个工作表,excel,user-defined-functions,vba,Excel,User Defined Functions,Vba,我有下面的代码,它从excel中的表创建一个数组,然后根据输入的多个条件搜索该数组 Function output_string(id As Long, dt As Date, descr As String) 'set variables Dim myarray As Variant Dim ws As Worksheet Dim col_count As Integer Dim row_count As Long Dim source_range As Range 'set worksh

我有下面的代码,它从excel中的表创建一个数组,然后根据输入的多个条件搜索该数组

Function output_string(id As Long, dt As Date, descr As String)

'set variables
Dim myarray As Variant
Dim ws As Worksheet
Dim col_count As Integer
Dim row_count As Long
Dim source_range As Range

'set worksheet
Set ws = Worksheets("Data Store")

dt = DateValue(app_dt)

'set up column and row counts for populated range
col_count = ws.Range("A2").End(xlToRight).Column
row_count = ws.Range("A2").End(xlDown).Row

'set range for populated cell space
Set source_range = ws.Range(Cells(2, 1), Cells(row_count, col_count))

'create the dimensions of the array that will store the table
ReDim myarray(1 To source_range.Rows.Count, 1 To source_range.Columns.Count)

'load data from excel table into array
myarray = source_range.Value


'get row with matching criteria
For i = LBound(myarray) To UBound(myarray)
    If myarray(i, 1) = id And dt >= myarray(i, 2) And dt <= myarray(i, 4) _
       And descr = myarray(i, 5) Then
       output_string = myarray(i, 3)
       Exit For
    End If
Next i

End Function
函数输出\u字符串(id为Long,dt为Date,descr为string)
'设置变量
Dim myarray作为变体
将ws设置为工作表
Dim COLU计数为整数
变暗行\按长计数
变暗源_范围作为范围
'设置工作表
设置ws=工作表(“数据存储”)
dt=日期值(app_dt)
'设置填充范围的列和行计数
col_count=ws.Range(“A2”).End(xlToRight).列
行计数=ws.Range(“A2”).End(xlDown).row
'设置填充单元格空间的范围
设置source\u range=ws.range(单元格(2,1),单元格(行计数,列计数))
'创建将存储表的数组的维度
ReDim myarray(1到source_range.Rows.Count,1到source_range.Columns.Count)
'将数据从excel表加载到数组中
myarray=source\u range.Value
'获取具有匹配条件的行
对于i=LBound(myarray)到UBound(myarray)

如果myarray(i,1)=id,dt>=myarray(i,2)和dt这一行,正如您在这里的评论中所提到的,是导致问题的原因:

'set range for populated cell space
Set source_range = ws.Range(Cells(2, 1), Cells(row_count, col_count))
问题是
单元格(2,1)
单元格(行计数、列计数)
都是工作表中未正确限定的范围对象。我知道这似乎违反直觉,因为您已经在这里说了
ws.range
,但是这些
range
对象也必须符合
ws

'set range for populated cell space
 Set source_range = ws.Range(ws.Cells(2, 1), ws.Cells(row_count, col_count))

如果没有该限定,它将使用
Application.Activesheet
作为默认值,这可能是您所在的UDF上下文中充当
Application.Caller.Parent
的工作表。因此,它试图在
ws
中创建一个范围,由
activesheet
中的开始和结束单元格组成,这是毫无意义的。

这非常有趣,感谢您的分享。在这一点上,我的问题可能还不清楚:我需要从
数据源
表生成数组,无论UDF在哪个表中使用。如果我理解正确,这一行
Set ws=Application.Caller.Parent
将在函数所在的同一工作表中生成数组。您知道有什么方法可以让数组每次都在
数据源
工作表上生成,并且在其他工作表中仍然可以使用该函数吗?也许我只需要将数组设为全局数组并对其进行函数调用?明白了。那就更有意义了。因为很难说为什么你会从这个东西中得到一个#值,也许在你的代码中设置一些断点并重新计算。查看“局部变量”窗格,查看分配给变量的值是否与期望值相匹配。引用UDF中的其他工作表没有问题。当在另一个工作表中使用时,但在
ws
工作表中使用时,这一行似乎崩溃了
Set source\u range=ws.range(单元格(2,1),单元格(行计数,列计数))
。你知道为什么会这样吗?代码很简单,我不知道哪里会出错。就是这样!对不起,我错过了。我已经更新了我的答案。是的!工作起来很有魅力。非常感谢你,你救了我!有趣的是,这么小的东西竟然会引起这么大的头痛。再次感谢!