尝试在两张纸上匹配一些数据

时间:2018-01-29 14:39:52

标签: excel vba excel-vba loops for-loop

我得到了

  

“类型不匹配”错误

我有以下代码循环遍历两张表,匹配数据并相应地填写列"C""D"。代码完全有效,直到我输入"And"语句,此时我收到"Type mismatch"错误,调​​试也突出显示该行。我无法弄清楚出了什么问题,任何帮助都会受到赞赏。

Sub ind_access_report()
Dim lastrow As Variant
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim x As Variant
Dim iName As String

    Set sh1 = ActiveWorkbook.Sheets("Sheet1")
    Set sh2 = ActiveWorkbook.Sheets("Sheet2")

iName = sh2.Range("A2").Value
lastrow = sh1.Cells(Rows.Count, "A").End(xlUp).Row

For x = 2 To lastrow

    If sh1.Range("C" & x).Value = iName _
  Then sh2.Range("C" & x + 3).Value = sh1.Range("A" & x).Value _
   And sh2.Range("D" & x + 3) = "OWNER"

    If sh1.Range("D" & x).Value = iName _
  Then sh2.Range("C" & x + 3).Value = sh1.Range("A" & x).Value _
   And sh2.Range("D" & x + 3) = "BACKUP"

    If sh1.Range("E" & x).Value = iName _
  Then sh2.Range("C" & x + 3).Value = sh1.Range("A" & x).Value _
   And sh2.Range("D" & x + 3) = "BACKUP"


Next x

2 个答案:

答案 0 :(得分:3)

您必须重新考虑换行策略。这是它失败的主要原因。如果您在Then之后有换行符,则需要End If 试试这个:

Sub ind_access_report()
    Dim lastrow As Variant
    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim x As Variant
    Dim iName As String

    Set sh1 = ActiveWorkbook.Sheets("Sheet1")
    Set sh2 = ActiveWorkbook.Sheets("Sheet2")

    iName = sh2.Range("A2").Value
    lastrow = sh1.Cells(Rows.Count, "A").End(xlUp).Row

    For x = 2 To lastrow

        If sh1.Range("C" & x).Value = iName Then
            sh2.Range("C" & x + 3).Value = sh1.Range("A" & x).Value
            sh2.Range("D" & x + 3) = "OWNER"
        End If

        If sh1.Range("D" & x).Value = iName Then
            sh2.Range("C" & x + 3).Value = sh1.Range("A" & x).Value
            sh2.Range("D" & x + 3) = "BACKUP"
        End If

        If sh1.Range("E" & x).Value = iName Then
            sh2.Range("C" & x + 3).Value = sh1.Range("A" & x).Value
            sh2.Range("D" & x + 3) = "BACKUP"
        End If

    Next x
End If

答案 1 :(得分:1)

您没有正确使用And。您可能正在尝试在If语句中执行多项操作。使用And并不是你如何做到的。相反,请使用多行和End If,如下所示:

If sh1.Range("C" & x).Value = iName Then 
    sh2.Range("C" & x + 3).Value = sh1.Range("A" & x).Value
    sh2.Range("D" & x + 3) = "OWNER"
End If