仅用于VBA用户定义的函数在工作簿中的一个工作表上工作

我有下面的代码,从Excel中的表创build一个数组,然后根据input的多个条件search该数组。

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 

该function给出正确的输出。 问题是该函数只适用于Data Store工作表。 所有其他工作表都会返回#VALUE! 当我input完全相同的input时出错。 该函数的参数可以是来自其他工作表的单元格引用而不会被误删。

此外,每隔一段时间(看似随机), Data Source选项卡上的工作function将从正确的值转换为#VALUE! 以及。

我在我正在使用的同一工作簿中的常规模块中具有该function。 该模块还有一个子程序。

我真的难住这一个。 有没有人看过/你知道一个解决scheme?

正如你在这里的评论中提到的那样,这条线正在引起这个问题:

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

问题是Cells(2,1)Cells(row_count, col_count)是没有正确限定其工作表的范围对象。 我知道这似乎是违反直觉的,因为你已经在这里说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创build一个范围在你的activesheet开始和结束的单元格是无稽之谈。