I have the below VB.Net code currently being executed in UiPath using the “Invoke Code” activity. The For
loop does not give any syntax errors but the If
statement does not seem to be executing. Is there a problem with the way I referenced the range in the loop (i.e., ws.range("F" & i).Value
)?
'create instances of excel and open final file
Dim excel As Microsoft.Office.Interop.Excel.Application
Dim wb As Microsoft.Office.Interop.Excel.Workbook
Dim ws As Microsoft.Office.Interop.Excel.Worksheet
excel = New Microsoft.Office.Interop.Excel.ApplicationClass
wb = excel.Workbooks.Open("FilePath.xlsx")
ws= DirectCast(wb.Worksheets(1),Microsoft.Office.Interop.Excel.Worksheet)
'Delete the first row of the worksheet
ws.Range("A1").EntireRow.Delete
'Define the last row of the worksheet
Dim LastRow As Long
LastRow = ws.UsedRange.Rows.Count
'Delete the last row (the Total column)
ws.Range("A" & LastRow).EntireRow.Delete
LastRow = ws.UsedRange.Rows.Count
Dim i As Long
For i = 2 To LastRow
If ws.range("F" & i).Value Is "Declined" Then
ws.range("F" & i).EntireRow.ClearContents
End If
Next i
'Save and close application
excel.activeworkbook.save
excel.Workbooks.close()
excel.Quit()
Your If
condition will always return false because Is
doesn't compare the content; it checks if two object references refer to the same object (yes, a string is an object), which in this case, is false.
Instead, you should use the =
operator to compare two strings. However, since the compile-time type of Range.Value
is Object
, you have to convert it to a string first. Change your code to something like this:
For i = 2 To LastRow
Dim currentCell = ws.Range("F" & i)
If currentCell.Value IsNot Nothing AndAlso currentCell.Value.ToString() = "Declined" Then
currentCell.EntireRow.ClearContents()
End If
Next