VB.Net For 循环无法执行



我有下面的VB.Net代码当前正在UiPath中使用"调用代码"活动执行。For循环没有给出任何语法错误,但If语句似乎没有执行。我在循环中引用范围的方式(即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()

您的If条件将始终返回false,因为Is不会比较内容;它检查两个对象引用是否引用了同一个对象(是的,字符串就是一个对象(,在这种情况下,这是false。

相反,您应该使用=运算符来比较两个字符串。但是,由于Range.Value的编译时类型是Object,因此必须先将其转换为字符串。将您的代码更改为这样的代码:

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

参考文献:

  • VB.NET中的比较运算符
  • Is运算符

最新更新