Late binding in Code

Hi devs, pls assist, I am having the error option strict on disallows late bindig in code, pls assist on the solution Dim groupedRows As IEnumerable(Of IGrouping(Of String, Microsoft.Office.Interop.Excel.Range))
From row In excelRange.Rows.Cast(Of Microsoft.Office.Interop.Excel.Range)()
Let brand As String = If(TryCast(row.Cells(1).Value2, Microsoft.Office.Interop.Excel.Range) IsNot Nothing, TryCast(row.Cells(1).Value2, Microsoft.Office.Interop.Excel.Range).ToString(), String.Empty)
Group row By brand Into Group
Select Group

Hi @RPA-botDev

Try this:

Dim groupedRows As IEnumerable(Of IGrouping(Of String, Microsoft.Office.Interop.Excel.Range)) =
    From row In excelRange.Rows.Cast(Of Microsoft.Office.Interop.Excel.Range)()
    Let brand As String = If(row.Cells(1).Value2 IsNot Nothing, DirectCast(row.Cells(1).Value2, String), String.Empty)
    Group row By brand Into Group
    Select Group

In this modified code:

  1. Replaced TryCast with DirectCast to explicitly cast the Value2 property to a String. This ensures that you are using early binding, and the compiler can check the types at compile-time.
  2. Removed the redundant check for TryCast(row.Cells(1).Value2, Microsoft.Office.Interop.Excel.Range) IsNot Nothing because you only need to check if Value2 is not Nothing. If it’s not Nothing, you can safely cast it to a String.

Hope it helps!!

1 Like

It’s still throwing late binding error, can you try it in your studio if it resolved pls

Hi @RPA-botDev
Try this:

groupedRows =From row In excelRange.Rows.Cast(Of Microsoft.Office.Interop.Excel.Range)()
             Let brand As String = If(row.Cells(1).Value2 IsNot Nothing, 
             DirectCast(row.Cells(1).Value2, String), String.Empty)
             Group row By brand Into Group
             Select Group

DataType of groupedRows: System.COllections.Generic.IEnumerable(System.Linq.IGrouping(System.String,Microsoft.Office.Interop.Excel.Range))

Hope it helps!!

It didn’t work out, any other better way to rewrite code pls