如果您废弃了 Excel 版本 MS365 及其UNIQUE() 函数,您可以尝试以下过程Examplecall 以及用户定义的帮助函数GetFormula() 和IsValid()。(如果没有很多例子,那么如何在以前的版本中获取唯一值).
这种方法还演示了以下常用 VBA 函数的使用
示例调用
Option Explicit ' force declarations at code module head
Sub ExampleCall()
With Sheet1 ' << change to wanted sheet Code(Name)
Dim rng As Range
Set rng = .Range("A2:B11") ' << change to wanted range (note the starting "."-point)
'a) get uniques array & provide for temporary results array
Dim uniques
uniques = .Evaluate(GetFormula(rng))
Dim results
results = uniques ' contains temporarily all uniques
End With
'b) mark all invalid items for deletion
Dim i As Long
For i = 1 To UBound(uniques)
If Not IsValid(uniques, i) Then results(i) = "$DEL$"
Next i
'c) remove marked items from results array
results = Filter(results, "$DEL$", False) ' negative filtering removes $DEL$ items
MsgBox Join(results, vbNewLine), vbInformation, "Found elements"
End Sub
帮助功能
Function GetFormula(rng As Range, Optional Delim As String = "-") As String
'a) define column number within the passed range argument
Const ITEM As Long = 1, STATUS As Long = 2 '
If rng.Columns.Count < Application.Max(ITEM, STATUS) Then Exit Function ' provide for sufficient columns
'b) define formula pattern
Dim Pattern As String
Pattern = "transpose(Unique(X & """ & Delim & """ & Y))" ' get unique combined strings
'c) replace range references X and Y with address string
GetFormula = Replace(Replace(Pattern, _
"X", rng.Columns(ITEM).Address(0, 0)), _
"Y", rng.Columns(STATUS).Address(0, 0))
End Function
Function IsValid(uniques, no As Long, _
Optional Exclude As String = "A", _
Optional Delim As String = "-") As Boolean
'a) get prefix of element no (i.e. string part before hyphen)
Dim ItemPrefix As String
ItemPrefix = Split(uniques(no), "-")(0) ' isolate string part before "-" via Split()
'b) filter items to be excluded
Dim tmp
tmp = Filter(uniques, ItemPrefix & Delim & Exclude, True) ' positive filtering of term to be excluded
'c) if there are no found items then return True as function result
If UBound(tmp) = -1 Then ' upper boundary -1 indicates empty 0-based array
IsValid = True ' return positive function result
End If
End Function