简体   繁体   English

Excel VBA类型不匹配错误

[英]Excel VBA Type mismatch error

I am trying to compare the values from one column of one sheet, with the values of another column of a different sheet, same workbook, though. 我正在尝试将一张工作表的一列中的值与另一张工作表的同一工作簿中的另一列中的值进行比较。 It steps through each cell in the other column, and if the cell value, a string, does not exist in sheet2, then the row from sheet1 is copied over to sheet3. 它逐步遍历另一列中的每个单元格,如果在sheet2中不存在该单元格值(字符串),则将sheet1中的行复制到sheet3。 You can think of it like I'm comparing two arrays. 您可以认为它就像我在比较两个数组。 I want to see if there are any values in Array1 that do not appear in Array2, and if they do not appear in Array1, the value is copied into Array3. 我想查看Array1中是否没有出现在Array2中的任何值,如果它们没有出现在Array1中,则将值复制到Array3中。

My main issue is I'm getting a type-mismatch error in line 5. The values contain strings. 我的主要问题是在第5行中收到类型不匹配错误。这些值包含字符串。 I am fairly new at Excel VBA and am trying to learn it on the fly. 我在Excel VBA上还很陌生,正在尝试快速学习它。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Sub search()
Dim count As Integer
count = 0

For Each i In Worksheets("Sheet1").Range("C2:C4503")
    Set first_cell = Worksheets("Sheet1").Cells(i, 3) <-- Mismatch eror

    For Each j In Worksheets("Sheet2").Range("X2:X4052")
        Set second_cell = Worksheets("Sheet2").Cells(j, 24)
        If second_cell = first_cell Then Exit For
    Next j

    count = count + 1
    Set Worksheets("Sheet3").Cells(count, 1) = Worksheets("Sheet1").Cells(j, 1).Select
Next i

End Sub 结束子

Sub Search()

Dim rowNum As Long
Dim i As Range, f As Range

    rowNum = 1

    For Each i In Worksheets("Sheet1").Range("C2:C4503").Cells

        If Len(i.Value) > 0 Then
            'search for value on sheet2
            Set f = Worksheets("Sheet2").Range("X2:X4052").Find( _
                             i.Value, , xlValues, xlWhole)

            If f Is Nothing Then
                'not found: copy row from sheet1>sheet3
                i.EntireRow.Copy Worksheets("Sheet3").Cells(rowNum, 1)
                rowNum = rowNum + 1
            End If
        End If

    Next i

End Sub

The following: 下列:

For Each i In Worksheets("Sheet1").Range("C2:C4503")
    ...
Next i

iterates through the cells in the specified range; 遍历指定范围内的单元格; i is a Range object representing the current cell. i是代表当前单元格的Range对象。

You are using it as in integer index in the following line: 您正在以下行中以整数索引形式使用它:

Set first_cell = Worksheets("Sheet1").Cells(i, 3)

Hence the Type Mismatch. 因此,类型不匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM