0

I am new to Excel VBA and I am working on a project which prints a report. I am getting an error when I run this excel VBA code. The error is at the "Columnoffset" line any help is appreciated. Thanks

Workbooks(MainWbName).Worksheets("DATA").Activate

rowoffset = DataRow - 1

' Activate WORKBOOK
Workbooks(MainWbName).Activate

Dim ColumnRangeName As String
Dim ColumnDefRange As Object
tabletouse = "ColumnDefinitions"
Sheettouse = "ColumnDefs"
Set ColumnDefRange = Worksheets(Sheettouse).Range(tabletouse)

If FieldTitle = " " Then Exit For

ColumnRangeName = WorksheetFunction.VLookup(FieldTitle, ColumnDefRange, 2, False)   

Columnoffset = Range(ColumnRangeName).Value   ' <-- Error

Workbooks(CSVFileName).Activate
braX
  • 11,506
  • 5
  • 20
  • 33

1 Answers1

0

Whenever you are working with VLookup, it is best to handle the error in case the lookup text is not found.

'
'~~> Rest of your code
'

Dim errorNumber As Long

On Error Resume Next
ColumnRangeName = WorksheetFunction.VLookup(FieldTitle, ColumnDefRange, 2, False)
errorNumber = Err.Number
On Error GoTo 0

If errorNumber <> 0 Then
    MsgBox FieldTitle & " not found"
Else
    Columnoffset = Range(ColumnRangeName).Value

    '
    '~~> Rest of your code
    '
End If

TIP: Also avoid the use of .Activate. You may want to see How to avoid using Select in Excel VBA

Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250