简体   繁体   English

VBA错误:类型不匹配

[英]VBA error : Type Mismatch

I want to look from a column in excel for the names "JOHN", "PETER", "ALAN", "ALI" with only one if statements as you see below. 我想从excel的一列中查找名称“ JOHN”,“ PETER”,“ ALAN”,“ ALI”,其中只有一个if语句,如下所示。 I got an error message Type mismatch. 我收到一条错误消息,类型不匹配。

Can any please help me? 能帮我吗?

Option Explicit

Sub name()

    Dim i As Long, nam As String
    nam = Array("JOHN", "PETER", "ALAN", "ALI")
    For i = 1 To 3000
        If Worksheets("CONTACTS").Cells(i, 1).Value = nam Then
            Worksheets("CONTACTS").Cells(i, 5).Value = "good"
        End If
    Next i

End Sub

I've reworked your loop through the worksheet cells into a bulk memory operation. 我将工作表单元格中的循环重做为大容量内存操作。

Sub name_check()
    Dim i As Long, n As Long, a As Long
    Dim nam As Variant, colAs As Variant

    nam = Array("JOHN", "PETER", "ALAN", "ALI")
    i = 3000

    With Worksheets("CONTACTS")
        colAs = .Cells(1, 1).Resize(i, 2).Value2

        For a = LBound(colAs, 1) To UBound(colAs, 1)
            colAs(a, 2) = vbNullString
            For n = LBound(nam) To UBound(nam)
                If UCase(colAs(a, 1)) = nam(n) Then
                    colAs(a, 2) = "good"
                    Exit For
                End If
            Next n
        Next a

        .Cells(1, 5).Resize(i, 1) = Application.Index(colAs, 0, 2)
    End With

End Sub

All of the looping and individual variable assignment is done within two variant arrays. 所有循环和单个变量分配都在两个变量数组中完成。 Only when those operations are complete are the results returned to the worksheet en masse . 只有当这些操作完成后是返回到工作表集体的结果。

There seem to be two issues: first, my excel complains with the array initialization, so i'm using variant instead of string; 似乎有两个问题:首先,我的excel抱怨数组初始化,所以我使用的是variant而不是string; second, poolie is right - loop through the array. 第二,poolie是正确的-遍历数组。 This should be what you want: 这应该是您想要的:

Sub Button1_Click()
 Dim i As Long, nam As Variant
    nam = Array("JOHN", "PETER", "ALAN", "ALI")
    For i = 1 To 30
        For j = 0 To UBound(nam)
            If Worksheets("CONTACTS").Cells(i, 1).Value = nam(j) Then
                Worksheets("CONTACTS").Cells(i, 5).Value = "good"
            End If
        Next j
    Next i
End Sub

在此处输入图片说明

You seem to be comparing the value to an array. 您似乎正在将值与数组进行比较。 You probably need to use a loop to check if the value in the cell is any of the names you're looking for. 您可能需要使用循环来检查单元格中的值是否是您要查找的任何名称。

(I'm not a VBA expert so I can't give you the code.) (我不是VBA专家,所以我不能给你代码。)

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

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