ActiveSheet.AutoFilter.Sort.SortFields.Clear in Excel 2003 - vba

I have a macro that works in Excel 2013, but the following part of the code breaks when running the macro in Excel 2003:
Sheets("dados").Select
Range("A1").AutoFilter Field:=6, Criteria1:="<>"
ActiveSheet.AutoFilter.Sort.SortFields.Clear
ActiveSheet.AutoFilter.Sort.SortFields.Add Key:=Range("A1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveSheet.AutoFilter.Sort.Apply
I wasn't able to find a clear reason why it is breaking. I read people mentioning the problem is the Sort object, but didn't find any replacement options. Is there a replacement for this filtering procedure which would work in Excel 2003?
I appreciate any help.

Try this one:
With ThisWorkbook.Sheets("dados")
.Range("A1").AutoFilter Field:=6, Criteria1:="<>"
.Range("A1").CurrentRegion.Sort Key1:=.Range("A1"), Order1:=xlAscending, _
Header:=xlYes, OrderCustom:=1, DataOption1:=xlSortNormal
End With

Related

Excel 2013 VBA use successive columns to sort large range

I've tried to research why this isn't working, but I've hit a wall, because, so far as I can tell, my code ought to be doing the trick...
My situation is that I'm building a spreadsheet to simplify a budget reporting process for my office. As I'm the only one with a half-decent understanding of Excel, I want to make this as braindead and simple for the other users as possible. To that end, VBA to the rescue! as it will take care of importing the data and doing all the sorting for me (them) with just one click.
The imported data is 24 columns wide and may grow to as much as 2500 lines by year-end. Once the data is imported, I need to sort by mulitple column types, one after the other, sucessively. So:
- Import data
- sort by date
- sort by transacation type
- sort by billed budget
- etc (6 sorts total)
This is my code at the moment:
Sub RefreshAll()
Workbooks(ThisWorkbook.Name).RefreshAll
With Worksheets("Detailed Budget Report")
.Range("RC_number").CurrentRegion.Sort _
key1:=Range("Sort_1st"), order1:=xlAscending, _
key2:=Range("Sort_2nd"), order2:=xlAscending, _
Header:=xlYes
End With
End Sub
The refresh all will pull from the import file anew, to make sure the spreadsheet is up-to-date. Then, I've got to sort it all. Thanks to the brilliant response at the bottom of this post, I learned about using range names, and this page showed me how to reference other worksheets.
Here's the problem: only the first sort key is working. The code doesn't throw an error, it doesn't halt, it appears to execute correctly. But, only the first sort argument gets actioned; no matter what range I input as the first key, nor what range I enter as the second, only the first gets sorted.
Can anybody help me figure out what I'm doing wrong?
Thanks in advance!
I have modified your code to use proper syntax. Note the difference.
Sub RefreshAll()
Workbooks(ThisWorkbook.Name).RefreshAll
With Worksheets("Detailed Budget Report").Sort
.SortFields.Clear
.SortFields.Add Key:=Range("Sort_1st"), Order:=xlAscending
.SortFields.Add Key:=Range("Sort_2nd"), Order:=xlAscending
.SetRange Range("RC_number")
.Header = xlYes
.Apply
End With
End Sub
Reminder: .SortFields.Clear may seem redundant but if you are applying multiple different sorts to the same sheet it can save some headache.
I have no idea why your code doesn't work on your computer as it works perfectly on mine. (I am running Excel 2007, though.)
In fact, all three of the appropriate methods (out of five total) to perform a sort in Excel work fine for me.
This is the one you haven't seen yet, using AutoFilter.Sort:
Sub RefreshAll_RS()
Workbooks(ThisWorkbook.Name).RefreshAll
With ActiveWorkbook.Worksheets("Detailed Budget Report")
.Range("RC_number").CurrentRegion.AutoFilter
.Range("RC_number").Select
With .AutoFilter.Sort
.Header = xlYes
.SortFields.Add Key:=Range("Sort_2nd"), Order:=xlAscending
.Apply
.SortFields.Clear
.SortFields.Add Key:=Range("Sort_1st"), Order:=xlAscending
.Apply
End With
.Range("RC_number").CurrentRegion.AutoFilter
End With
End Sub
Then there's your version, using Range.Sort. (I've modified it slightly but it's still functionally equivalent.)
Sub RefreshAll_Q1()
Workbooks(ThisWorkbook.Name).RefreshAll
With Worksheets("Detailed Budget Report").Range("RC_number").CurrentRegion
.Sort _
key1:="Sort_1st", order1:=xlAscending, _
key2:="Sort_2nd", order2:=xlAscending, _
Header:=xlYes
End With
End Sub
And finally, there's Joshua's version, using Worksheet.Sort. (I've fixed the incorrect .SetRange parameter bug, so it now works.)
Sub RefreshAll_A1()
Workbooks(ThisWorkbook.Name).RefreshAll
With Worksheets("Detailed Budget Report").Sort
.SortFields.Clear
.SortFields.Add Key:=Range("Sort_1st"), Order:=xlAscending
.SortFields.Add Key:=Range("Sort_2nd"), Order:=xlAscending
.SetRange Range("RC_number").CurrentRegion
.Header = xlYes
.Apply
End With
End Sub

Excel VBA: Paste clipboard data (external source) with the appropriate cell data type

I am copying table data (tab delimited) many times a day from external sources (other applications such as sqlClients: Heidi, MS SQL Management Studio, inhouse tools, ...) and pasting them in Excel sheets for extended analysis.
I've been struggling to make a macro that pastes specific columns in the correct format instead of the General type which alters how data is displayed.
At first I tried setting up specific columns to the appropriate dataType before using paste special to paste values only:
ActiveSheet.Range("B:D,X:X").NumberFormat = "#"
ActiveSheet.Range("A1").PasteSpecial _
Paste:=xlPasteValues _
, Operation:=xlNone _
, SkipBlanks:=False _
, Transpose:=False
Sadly it gives Run Time Error '1004' PasteSpecial method of Range class failed which I couldn't solve.
Next I tried TextToColumns follows:
ActiveSheet.Range("A1").Select
ActiveSheet.Paste
For Each cell In Selection.Cells
If cell <> "" Then
cell.TextToColumns _
Destination:=cell _
, DataType:=xlDelimited _
, ConsecutiveDelimiter:=False _
, Space:=False _
, TextQualifier:=xlTextQualifierNone _
, Tab:=True _
, semicolon:=False _
, comma:=False _
, other:=False _
, FieldInfo:=Array(Array(0, 2), Array(1, 2), Array(3, 2), Array(10, 2), Array(15, 2))
End If
Next
Not only it doesn't work as expected (what is wrong with it ?), but it doesn't seem efficient as It pastes the clipboard content before looping over every cell. My tables can be really huge and thus this will take a lot of time!
So, I was wondering if there is a better/elegant way to paste the clipboard data from an external source into the appropriate cell data type. If not, helping fixing the above leads would be nice as well.
Thank you in advance <3
Edit.1:
Now that I have some correct code working thanks to #jivko's comment:
ActiveSheet.Range("A1").Select
ActiveSheet.PasteSpecial Format:="Unicode Text", Link:=False, DisplayAsIcon:=False
Since I'm pasting code from different sources with different number of columns, I was wondering how could I know how many columns are there in the clipboard before pasting so I can apply the appropriate format beforehand ?
An idea would be to Paste > Count the columns > Apply the correct Format > Paste again. It doesn't sounds perfect but it should get the job done.
If you have any better solution please feel free to share <3
I use a Macro to paste my data, and I've inserted this code near the start. It prevents double quotes (at the start of an entry) from being a problem.
'This section prevents any special characters from interfering with the paste by specifying TextQualifier:=xlNone:
Range("A1").Select
ActiveCell.FormulaR1C1 = "abc"
Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlNone, ConsecutiveDelimiter:=False, Tab:=True, Semicolon _
:=False, Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(1, _
1), TrailingMinusNumbers:=True
Range("A1").Select
Selection.ClearContents
'End Section

Excel VBA autofilter uncheck/exclude items

quick question, how can I exclude an item in a list through VBA. Have been working on a sheet that automatically prints out a list without a certain date on it.
Rows("2:2").Select
Selection.AutoFilter
ActiveSheet.Range("$A$3:$H$1000").AutoFilter Field:=3, Criteria1:="Hans"
ActiveSheet.Range("$A$3:$H$1000").AutoFilter Field:=7, Criteria1:="open"
ActiveSheet.Range("$A$3:$H$1000").AutoFilter Field:=6, Criteria1:="<>1/0/1900", Operator:=xlFilterValues
ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
IgnorePrintAreas:=False
Rows("3:3").Select
Selection.AutoFilter
Problem is that the criteria does not work with the date 0-1-1900 to filter it out. What am I doing wrong?
0-1-1900 is a date that does not exist. This might be the problem.
Just use
Criteria1:=">1/1/1900"
and it should word fine.

Unprotecting then Protecting Sheet

Part 1
I have put together the following code in order to sort data on a sheet.
However, users keep deleting rows from the sheet which ruins the rest of my workbook so I have protected the sheet but then the macro will not longer run.
Can someone help me with the code to unprotect the sheet, run the macro and re protect the sheet at the end?
Sub CustSort1()
Range("a14").Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.Sort Key1:=Range("a14"), Order1:=xlAscending, Key2:=Range( _
"k14"), Order2:=xlAscending, _
Header:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:= _
xlTopToBottom, DataOption1:=xlSortNormal, DataOption2:=xlSortNormal, _
DataOption3:=xlSortNormal
Range("a14").Select
End Sub
I have found similar posts but my level of knowledge is pretty low.
All help appreciated.
Part 2
Ok so small issue has come up! What if I still want the user to be able to insert cells?
I can see I need to use this "AllowInsertingRows" but dont understand where i insert it.
Absolutely agree with #vba4all. Another way of writing is to unprotect the worksheet before you call CustSort1 sub routine and then protect the worksheet again.
Sub pMainCode()
'Considering Sheet1 to be where you want to apply sorting
Worksheets("Sheet1").Unprotect "Password"
Call CustSort1
Worksheets("Sheet1").Protect "Password"
End Sub

Sort a Column in Another Sheet Without Selecting That Sheet

Is it possible to sort columns in another sheet without selecting that sheet?
The problem is while I am running this code, I want this sheet to be hidden and I do not want it to flash over to it when I need to sort the table. Here is my code... This works, but it does obviously select the sheet and shows you the other sheet. Maybe something with 'make active sheet' would work can you do that then say 'make active cell'. I am not sure. Thanks guys.
Application.Worksheets("RawDataLines").Select
Application.Worksheets("RawDataLines").Range("Q5").Select
Application.Worksheets("RawDataLines").Range("A4:R1007").Sort Key1:=Range("Q5"), Order1:=xlAscending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
Application.Worksheets("RawDataLines").Range("A5").Select
Application.Worksheets("RawDataLines").Range("A4:R1007").Sort Key1:=Range("A5"), Order1:=xlAscending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
This:
Application.Worksheets("RawDataLines").Select
Application.Worksheets("RawDataLines").Range("Q5").Select
Application.Worksheets("RawDataLines").Range("A4:R1007").Sort ...
Could be this:
With Application.Worksheets("RawDataLines")
.Range("A4:R1007").Sort Key1:= .Range("A5")'...
End With
Add ScreenUpdating
Application.ScreenUpdating = False
#Your Code
Application.ScreenUpdating = True
Just make sure that you set the select back to the sheet you want it on prior to setting ScreenUpdating = True
Here the problem comes with the Key1 arguments of VBA sort method. Even though we explicitly pass range with relevant sheet, when it comes to Key1:=Range(…), VBA automatically take ActiveSheet.Range(…).
If We have selected some other sheet instead of the sheets of sort data, VBA shows runtime error.
To fix this problem change the code as Key1:=Your_Sheet_With_Data.Range(Your_Range). For Example, above referred code can be fixed changing the code as
Key1:=Worksheets("RawDataLines").Range("Q5")