NorthbyNorthwest
Board Regular
- Joined
- Oct 27, 2013
- Messages
- 173
- Office Version
- 365
Hi, everyone. I have a macro that sorts a table by employee names. Because each name is first last and share a cell, I have a second macro that flips the names to last first before alphabetizing them and flips them back afterwards. Everything worked just fine until recently when the flip name macro began triggering runtime error "Select method of range class failed." Can someone help?
VBA Code:
Sub AlphaZulu()
Dim oSheetName As Worksheet
Dim sTableName As String
Dim loTable As ListObject
Dim rRange1 As Range
'Alphabetize table
Application.EnableEvents = False
Application.ScreenUpdating = False
Sheets("Tables").Activate
Call FlipName4Sort
'Define Variable
sTableName = "tblEmployee"
'Define WorkSheet object
Set oSheetName = ActiveSheet
'Define Table Range
Set rRange1 = Range("tblEmployee[Employee]")
'Define Table Object
Set loTable = oSheetName.ListObjects(sTableName)
'Sort Single Column Table
With loTable.Sort
'specify header is available or not
.Header = xlYes
'Clear if any existing sort
.SortFields.Clear
'Specify Column to sort
.SortFields.Add Key:=rRange1, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
'sort specified column in a table
.Apply
End With
Call FlipName4Sort
Sheet9.Range("J5").Select
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
VBA Code:
Sub FlipName4Sort()
'Reverse names in column B of Employee table
Application.EnableEvents = False
Range("tblEmployee[Employee]").Select
On Error Resume Next
iRows = Selection.Rows.Count
Set lastcell = Cells.SpecialCells(xlLastCell)
mrow = lastcell.Row
If iRows > mrow Then iRows = mrow
imax = -1
For ir = 1 To iRows
checkx = Trim(Selection.Item(ir, 1))
L = Len(Trim(Selection.Item(ir, 1)))
If L < 3 Then GoTo nextrow
For im = 2 To L
If Mid(checkx, im, 1) = "," Then GoTo nextrow
If Mid(checkx, im, 1) = " " Then imax = im
Next im
If imax > 0 Then
Selection.Item(ir, 1) = Trim(Mid(checkx, _
imax, L - imax + 1)) & " " & _
Trim(Left(checkx, imax))
End If
nextrow:
Next ir
terminated:
Application.EnableEvents = False
End Sub