Running a quick test with an Optional Variant, using the IsMissing
function shows that Nothing
is not the same as Missing
:
Option Explicit
Private Function IsItMissing(Optional vTMP As Variant) As Variant
IsItMissing = CVErr(xlErrNA)
On Error GoTo FuncErr
IsItMissing = IsMissing(vTMP)
FuncErr:
End Function
Public Sub TestValues()
MsgBox IsItMissing("Nope") 'False
MsgBox IsItMissing 'True
MsgBox IsItMissing(Nothing) 'False
End Sub
The problem is that Nothing
is a Special Object, rather than actually being 'nothing'. It's like the difference in Excel between a Blank cell and a cell with no data (e.g. =""
)
I suspect you would want to chain If
statements with Is Nothing
to create your sort:
If fdsKey2 Is Nothing Then
loFinalReport.DataBodyRange.Sort Header:=xlYes, _
Key1:=fdsKey1, Order1:=fdsSortOrders(0)
ElseIf fsdKey3 Is Nothing Then
loFinalReport.DataBodyRange.Sort Header:=xlYes, _
Key1:=fdsKey1, Order1:=fdsSortOrders(0), _
Key2:=fdsKey2, Order2:=fdsSortOrders(1)
Else
loFinalReport.DataBodyRange.Sort Header:=xlYes, _
Key1:=fdsKey1, Order1:=fdsSortOrders(0), _
Key2:=fdsKey2, Order2:=fdsSortOrders(1), _
Key3:=fdsKey3, Order3:=fdsSortOrders(2)
End If
{EDIT:Following discussions in comments} Here is a function which uses 2 arrays to work out which, if any, of the Keys are not Nothing:
Private Function SortNothing(Target As Range, Optional Key1 As Variant, Optional Order1 As XlSortOrder = xlAscending, Optional Key2 As Variant, Optional Order2 As XlSortOrder = xlAscending, Optional Key3 As Variant, Optional Order3 As XlSortOrder = xlAscending) As Boolean
Dim iArr As Integer, aKeys(1 To 3) As Variant, aOrders(1 To 3) As XlSortOrder
iArr = 0 'This pointer will track how many non-Nothing Keys we have
SortNothing = False
On Error GoTo FuncErr
If Not IsMissing(Key1) Then
If Not (Key1 Is Nothing) Then
iArr = iArr + 1
aKeys(iArr) = Key1
aOrders(iArr) = Order1
End If
End If
If Not IsMissing(Key2) Then
If Not (Key2 Is Nothing) Then
iArr = iArr + 1
aKeys(iArr) = Key2
aOrders(iArr) = Order2
End If
End If
If Not IsMissing(Key3) Then
If Not (Key3 Is Nothing) Then
iArr = iArr + 1
aKeys(iArr) = Key3
aOrders(iArr) = Order3
End If
End If
Select Case iArr
Case 3:
Target.Sort Key1:=aKeys(1), Order1:=aOrders(1), Key2:=aKeys(2), Order2:=aOrders(2), Key3:=aKeys(3), Order3:=aOrders(3), Header:=xlYes
Case 2:
Target.Sort Key1:=aKeys(1), Order1:=aOrders(1), Key2:=aKeys(2), Order2:=aOrders(2), Header:=xlYes
Case 1:
Target.Sort Key1:=aKeys(1), Order1:=aOrders(1), Header:=xlYes
End Select
SortNothing = True
FuncErr:
End Function