VB.Net For 循环不会执行

VB.Net For Loop won't execute

我有以下 VB.Net 当前正在 UiPath 中使用“调用代码”activity 执行的代码。 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 条件将始终 return 错误,因为 Is 不比较内容;它检查两个对象引用是否引用同一个对象(是的,一个字符串是一个对象),在这种情况下,它是错误的。

相反,您应该使用 = 运算符来比较两个字符串。但是,由于 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

参考文献: