Excel UDF返回#value!更改工作表和复制和粘贴时

时间:2013-12-28 22:16:03

标签: excel vba excel-vba user-defined-functions

我有一张表上有一张表,下面的函数将用于搜索另一张表并返回代理商名称显示的次数;

我遇到的问题是,如果我尝试复制并粘贴该值,它将从一个数字变为'#Value!'。此外,当切换工作表然后切换回调用UDF的工作表时,它会将所有值更改为“#Value!”

这是函数及其调用方式。任何帮助将不胜感激。

Public Function GetMatrixCount(AgentName As String) As Integer
Dim matrixSheet As Worksheet, mContainer() As String, c As Integer, m As Integer, y As Integer
Dim fullRange As Range, l As Range, lastRow As Integer
Dim firstThree As String, curAgent As String

'toDo
'return zero if the matrix updates worksheet doesn't exist or the input string is empty
On Error Resume Next
Set matrixSheet = Sheets("Matrix Updates")
On Error GoTo 0
If matrixSheet Is Nothing Or Not Trim(AgentName) <> "" Then
    GetMatrixCount = 0
    Exit Function
End If

'get month number user wants to input from the title at the top of the page - used to do value check on matrix updates data
mContainer() = Split(Range("B1").Value, " ")
m = month(DateValue(mContainer(UBound(mContainer) - 1) & " 1"))
y = mContainer(UBound(mContainer))
firstThree = Left(AgentName, 3)
lastRow = matrixSheet.Cells(Rows.Count, 1).End(xlUp).Row
c = 0

Set fullRange = matrixSheet.Range("B2:B" & lastRow)
For Each l In fullRange.Cells
    curAgent = l.Offset(0, 1).Value
    If month(l.Value) = m And year(l.Value) = y And Left(curAgent, 3) = firstThree And Mid(curAgent, InStrRev(curAgent, " ") + 1) = Mid(AgentName, InStrRev(AgentName, " ") + 1) Then
        c = c + 1
    End If
    If l.Value = "" Then
        Exit For
    End If
Next

GetMatrixCount = c
End Function

使用方法: = GetMatrixCount(B4)

B4:John Doe

1 个答案:

答案 0 :(得分:0)

<强> UPD: 试着写下面的内容:

Set wb = ThisWorkbook
Set matrixSheet = wb.Sheets("Matrix Updates")

切换工作簿时应该解决问题。

相关问题