I'm scratching my head here and really hope someone can point me in the right direction.
I'm trying to create a VBA function to count unique occurances of text within a range and am using a variation of code found online to achieve that.
Essentially the code (below) does the following:
- Create a temporary workbook
- Copies a deduplicated list of the text across to that workbook
- Count how many rows that equates to.
This is the code I have so far:
Public Function TestingMe() As Long
Dim numrows As Long
Dim rng As Range
Dim tempwb As Workbook, origwb As Workbook
Set origwb = ActiveWorkbook
Set tempwb = Workbooks.Add
Set rng = tempwb.Sheets(1).Range("A1")
origwb.Worksheets("data").Range("A:A").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=rng, Unique:=True
numrows = tempwb.Application.WorksheetFunction.CountA(tempwb.Sheets(1).Range("A:A").EntireColumn)
tempwb.Close (False)
Set origwb = Nothing
Set tempwb = Nothing
Debug.Print (numrows)
TestingMe = numrows
End Function
The code works perfectly fine when ran through the Immediate window of the code editor, but when used as a function from within a worksheet the "COUNTA" function is looking at the first sheet of the origwb rather than the temporary workbook where the de-duplicated data has been copied to.
It seems like it's a reference/scoping issue but as you can see, I've tried in the code to specifically reference everthing to attempt to fix the issue but with no joy.
Any pointers would really be appreciated.
Thanks in advance Martin