KentBurel
Board Regular
- Joined
- Mar 27, 2020
- Messages
- 68
- Office Version
- 2019
- Platform
- Windows
I'm getting an error 1004 Method 'Range' of object '_Global' failed. I have a spreadsheet that I use VLOOKUP on. So I name the range of the table and use it in formulas. But not I have to update that table. Rows might be added or deleted. So I have a macro to run after the table is updated that will update the Named ranges and also sort the table in order. I ran the macro recorder to capture the Data Sort commands. Then the macro has to be changed to used the name ranges instead of the fixed cell references created by the macro recorder. I created some temporary Names so I could verify that the column1 and column2 ranges were correct. I get the error message on the first ActiveWorkbook.Worksheets("BMD Master").Sort.SortFields.Add2 statement. Your help is greatly appreciated.
VBA Code:
Option Explicit
Sub SortBMDMasterTable()an the f
'
' SortBMDMasterTable Macro
' This macro sorts the BMD master table. The table must stay sorted because it is used by the VLOOKUP functions in the Precinct sheets to prefill the data.
'
Dim firstRow As Integer, lastRow As Integer
Dim myRange As Range
Dim myRange2 As Range
Dim myColumn1 As Range
Dim myColumn2 As Range
firstRow = 19 'Row 19 is the first line of the BMDMaster table
ActiveWorkbook.Worksheets("BMD Master").Select
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
Set myRange = Range("A" & firstRow & ":F" & lastRow)
On Error Resume Next
Names("BMDData").Delete ' Delete the "BMDData" named range
On Error GoTo 0
myRange.Name = "BMDData" ' Add the "BMDData" back
Set myRange2 = Application.Union(Range("BMDHeader"), myRange)
myRange2.Name = "myRange2"
Set myColumn1 = myRange.Resize(, 1)
Set myColumn2 = myRange.Offset(, 1).Resize(, 1)
ActiveWorkbook.Worksheets("BMD Master").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("BMD Master").Sort.SortFields.Add2 Key:=Range( _
myColumn1), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
ActiveWorkbook.Worksheets("BMD Master").Sort.SortFields.Add2 Key:=Range( _
myColumn2), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("BMD Master").Sort
.SetRange Range("myRange2")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub