VBA错误:types不匹配

我想从excel的专栏中看到名字“JOHN”,“PETER”,“ALAN”,“ALI”,只有一个if语句,如下所示。 我收到错误消息types不匹配。

任何人都可以帮我吗?

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 

似乎有两个问题:首先,我的Excel与数组初始化抱怨,所以我使用变体而不是string; 第二,poolie是正确的 – 通过arrays循环。 这应该是你想要的:

 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 

在这里输入图像说明

我已经通过工作表单元将您的循环重新编译为批量存储器操作。

 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 

所有的循环和个体variables赋值都在两个变体数组中完成。 只有当这些操作完成后,结果才能返回到工作表。

您似乎将该值与数组进行比较。 您可能需要使用循环来检查单元格中的值是否是您正在查找的任何名称。

(我不是VBA专家,所以我不能给你代码。)