Greetings, all!
In a nutshell, what I have is a command button which executes code that loops through rows on a different worksheet ("Work Data") and copy/pastes rows that fit the criteria (in this case, user-entered date) into a 3rd worksheet ("Query Output").
This works fine, but I am trying to then sort the rows in ascending order by column "G" (which can have a varying number of rows in it).
If I do this manually and record it as a macro I get the bottom portion of the code below. As it's own module run with a hotkey after the macro pastes data into the Query Output tab, it does the sorting just fine. However, if I stick the same code into the private sub as shown below, I get a "Run-time error '1004', Selected method of range class failed" error.
Am I overlooking something?
![]()
Private Sub CommandButton3_Click() Const csQuery As String = "Query Output" Dim sPartNumber As String Dim rFind As Range Dim rRows As Range Dim rData As Range Dim sFirstMatch As String Dim ws As Worksheet sPartNumber = InputBox("Please enter the Date (ex: 6/5/2013):") If sPartNumber = "" Then Exit Sub Set rData = ThisWorkbook.Worksheets("Work Data").Columns("A") Set rFind = rData.Find(sPartNumber) If rFind Is Nothing Then MsgBox "There were no matches.", vbInformation Else sFirstMatch = rFind.Address Do If rRows Is Nothing Then Set rRows = rFind Else Set rRows = Union(rRows, rFind) End If Set rFind = rData.FindNext(rFind) Loop While rFind.Address <> sFirstMatch On Error Resume Next Set ws = ThisWorkbook.Worksheets(csQuery) On Error GoTo 0 If ws Is Nothing Then Set ws = ThisWorkbook.Sheets.Add ws.Name = csQuery End If ws.Cells.Delete ThisWorkbook.Worksheets("Work Data").Rows(1).Copy ws.Rows(1) rRows.EntireRow.Copy ws.Rows(2).PasteSpecial xlPasteValues rRows.Parent.Cells.Copy ws.Rows.PasteSpecial xlPasteFormats End If Worksheets("Query Output").Activate ActiveSheet.Range("A1").Select Application.CutCopyMode = False 'Below is the code generated by the Macro Recorder Columns("G:G").Select ActiveWorkbook.Worksheets("Query Output").Sort.SortFields.Clear ActiveWorkbook.Worksheets("Query Output").Sort.SortFields.Add Key:=Range("G1" _ ), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal With ActiveWorkbook.Worksheets("Query Output").Sort .SetRange Range("A2:W4980") .Header = xlNo .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With











LinkBack URL
About LinkBacks
Register To Reply
Bookmarks