简体   繁体   中英

I am having an issue with <method range of object _global failed> error

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM