Hi Greg,
it looks like you have an autofilter on when you are running
ive extended your code for the autofilter to handle this and an attept to handle the case if the name is missing
you can try it and see if it fits your needs
Code:
'sub name changed as it was causing an object conflict
Sub AddAutofilter()
Dim tmp1 As String
Dim bCheckName As Boolean
Dim wks As Worksheet
Dim rng As Range
Dim rngForName As Range
'set up object references
Set wks = ActiveSheet
Set rng = Selection
'adjust rng to be the top left cell of selection
'delete if inappropriate
If Not rng.Column = 1 Then
If Not IsEmpty(rng.Offset(0, -1)) Then Set rng = rng.End(xlToLeft)
End If
If Not rng.Row = 1 Then
If Not IsEmpty(rng.Offset(-1, 0)) Then Set rng = rng.End(xlUp)
End If
'switch autofilter off if its on
If wks.AutoFilterMode Then wks.AutoFilterMode = Not wks.AutoFilterMode
'Check through the names in the worksheet if it doesnt exist try to add it
For Each nme In Application.Names
If nme = "SoldLogLastWeeksDate" Then
bCheckName = True
Exit For
End If
Next nme
'trying to add the autofilter
If Not bCheckName Then
'find the correct location, adjust to your needs
Set rngForName = wks.Cells.Find("Last weeks Date").Offset(0, 1)
'if it isnt found infor user and drop out of sub
If rngForName Is Nothing Then
MsgBox "Please Define the Name SoldLogLastWeeksDate and rerun"
Exit Sub
End If
'define the name in the new location
Application.Names.Add "SoldLogLastWeeksDate", _
"=" & wks.Name & "!" & rngForName.Address
End If
'define criteria using doubles to prevent filter error
'without it it shows nothing
tmp1 = CDbl(Range("SoldLogLastWeeksDate").Value)
tmp1 = ">" & tmp1
'set the criteria of the autofilter, adjust number formats to prevent error
'could use entirecolumn here but have set a range
'as i dont know what else is in the column
Range(rng, rng.End(xlDown)).NumberFormat = "0"
rng.Autofilter Field:=1, Criteria1:=tmp1
'reset numberformat
Range(rng, rng.End(xlDown)).NumberFormat = "dd/mm/yyyy"
'set object variables to nothing
Set rng = Nothing
Set rngForName = Nothing
End Sub
Dave