【发布时间】:2017-12-12 16:38:31
【问题描述】:
我有以下代码,它从 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
函数给出正确的输出。问题是该函数仅适用于Data Store 工作表。当我输入完全相同的输入时,所有其他工作表都会返回 #VALUE! 错误。该函数的参数可以是来自其他工作表的单元格引用,而不会出错。
此外,每隔一段时间(似乎是随机的)Data Source 选项卡上的工作函数也会从正确的值转换为 #VALUE!。
我在使用的同一个工作簿中的常规模块中具有该功能。该模块中还有一个子程序。
我真的被这个难住了。有没有人见过这个/你知道解决方案吗?
【问题讨论】:
标签: excel user-defined-functions vba