Visual Basic如果然后错误

我有一个VB项目,我试图使用一些基于Excel工作表的第一列find重复行的VBA代码,并创build一个“1”的标志,但在VB中使用时,VBA代码给出的错误:

InvalidCastException未处理重载parsing失败,因为没有公共'<>'可以用这些参数调用:公共共享运算符(一个作为string,b作为string)作为布尔':参数匹配参数'a'不能从'__ComObject '到'string'。

Public Sub btnRun_Click(sender As System.Object, e As System.EventArgs) Handles btnRun.Click Dim xlApp As Excel.Application Dim xlWorkBook1 As Excel.Workbook ' Interactions Dim xlWorkBooks As Excel.Workbooks Dim MainSheet1 As Excel.Worksheet xlApp = New Excel.Application xlWorkBooks = xlApp.Workbooks xlWorkBook1 = xlWorkBooks.Open(File1_name) xlApp.Visible = False MainSheet1 = xlWorkBook1.Sheets(1) MainSheet1.Activate() Dim InteractionRows As Long = MainSheet1.UsedRange.Rows.Count ' Total number of rows in the Interaction worksheet Dim Duplicate_Found_Index As Long ' Stores all match index values for duplicate interactions Dim Duplicate_ID As Long ' Defining the first column to loop through and match duplicate interactions ' **** Duplicate Interaction **** ' Flag Creation For Duplicate_ID = 1 To (InteractionRows) If MainSheet1.Cells(Duplicate_ID, 1) <> "" Then 'checking if the cell is having any item, skipping if it is blank. Duplicate_Found_Index = xlApp.WorksheetFunction.Match(MainSheet1.Cells(Duplicate_ID, 1), MainSheet1.Range("A1:A" & InteractionRows), 0) 'getting match index number for the value of the cell. If Duplicate_ID <> Duplicate_Found_Index Then 'if the match index is not equals to current row number, then it is a duplicate value MainSheet1.Cells(Duplicate_ID, 34) = "1" ' Print the flag "1" in the 34th column if duplicate found Else MainSheet1.Cells(Duplicate_ID, 34) = "0" ' Print the flag "0" in the 34th column if no duplicate End If End If Next End Sub 

任何援助将大大理解为什么这个错误发生

当单元格为空时,调用MainSheet1.Cells(Duplicate_ID,1)将返回Nothing(null)。 所以,而不是匹配一个string,检查它为空值。

 If MainSheet1.Cells(Duplicate_ID, 1) IsNot Nothing Then End If 

使用IsNot来代替<>

  If Duplicate_ID IsNot Duplicate_Found_Index Then 'if the match index is not equals to current row number, then it is a duplicate value MainSheet1.Cells(Duplicate_ID, 34) = "1" Else MainSheet1.Cells(Duplicate_ID, 34) = "0" End If