【问题标题】:Trying to match some data across two sheets试图在两张纸上匹配一些数据
【发布时间】:2018-01-29 14:39:51
【问题描述】:

我明白了

“类型不匹配”错误

我有以下代码循环遍历两张表,匹配数据并相应地填写"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

【问题讨论】:

  • 我确信 Google 上一定有关于此的内容。 Then 之后的语句必须在单独的行中并且没有 And
  • 我在其他宏中之前在一行中使用了If... Then... And 语句,没有任何问题。这不是一个真正的 googleable 问题。
  • 对不起,我误读了您的代码。你有任何错误值吗?
  • And 用作If 的一部分,而不是Then 的一部分
  • 我的错误值是Type Mismatch,不幸的是,没有其他可以参考。我不明白为什么AndIf 的一部分而不是Then 如果它在Then 之后?

标签: vba excel loops for-loop


【解决方案1】:

您将不得不重新考虑您的换行策略。这是它失败的主要原因。如果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

【讨论】:

  • 是的,这个有效。不过,我不需要在Next x 之后加上End If,非常感谢。不知道换行会导致问题,我认为这只是为了让代码看起来更整洁。
  • VBA 是一种古老的语言。换行符在这里的处理方式与更现代的语言不同。
【解决方案2】:

您没有正确使用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

【讨论】:

  • 我之前尝试过And,我只是得到End if without Block if 错误。
  • 那么您需要更仔细地查看If 语句的结构。
猜你喜欢
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多