Question

I have a sheet that has a table on it, the following function will be used to search another sheet and return the number of times the agents name shows up;

The problem I'm having is that if I try to copy and paste the value it will change from a number to '#Value!'. Also, when switching worksheets and then switching back to the worksheet that has the UDF being called it changes all values to '#Value!'

Here is the function and how it is called. Any help would be greatly appreciated.

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

Usage: =GetMatrixCount(B4)

B4: John Doe

Was it helpful?

Solution

UPD: Try to write following:

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

It should fix the problem when you switch workbooks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top