【问题标题】:Excel VBA to copy adjacent column in different sheet based on matching criteriaExcel VBA根据匹配条件复制不同工作表中的相邻列
【发布时间】:2014-10-21 17:07:38
【问题描述】:

我有一个宏来检查 sheet1 列 A 中的值是否与 sheet2 中同一列中的值匹配,如果是,它将每个匹配值的相邻单元格从 sheet1 复制到 sheet2 中。以下是我到目前为止的内容,但我在 lastrowadd 行上不断收到“运行时错误 9”,但不知道为什么。任何帮助将不胜感激:)

Sub CopyAdjacent()
    Dim i As Long, j As Long, colStatus As Long, lastrowAdd As Long, lastrowRemove As Long

    colStatus = 2 'your status column number
    lastrowAdd = Sheets(“Sheet1”).Cells(Sheets(“Sheet1”).Rows.Count, 1).End(xlUp).Row
    lastrowRemove = Sheets(“Sheet2”).Cells(Sheets(“Sheet2”).Rows.Count, 1).End(xlUp).Row

    For i = 1 To lastrowAdd
        For j = 1 To lastrowRemove
            If Sheets(“Sheet1”).Cells(i, 1).Value = Sheets(“Sheet2”).Cells(j, 1).Value Then
                Sheets(“Sheet2”).Cells(j, colStatus).Value = Sheets(“Sheet1”).Cells(i, colStatus).Value
            End If
        Next j
    Next i
End Sub

【问题讨论】:

  • Sheets(“Sheet1”).Cells(Sheets(“Sheet1”).Rows.Count, 1).End(xlUp).Row 尝试将其更改为 Sheets(“Sheet1”).Rows.Count-1 看看会发生什么
  • 它仍然给出相同的结果。

标签: vba excel


【解决方案1】:

进行了一些小的更改,包括定义 lastrowAdd 和 lastrowRemove 的方式。我还从定义中删除了i 和j。

Sub CopyAdjacent()
Dim colStatus As Long, lastrowAdd As Integer, lastrowRemove As Integer

colStatus = 2
lastrowAdd = Sheets(“Sheet1”).Cells(Rows.Count, 1).End(xlUp).Row
lastrowRemove = Sheets(“Sheet2”).Cells(Rows.Count, 1).End(xlUp).Row

For i = 1 To lastrowAdd
    For j = 1 To lastrowRemove
        If Sheets(“Sheet1”).Cells(i, 1).Value = Sheets(“Sheet2”).Cells(j, 1).Value Then
            Sheets(“Sheet2”).Cells(j, colStatus).Value = Sheets(“Sheet1”).Cells(i, colStatus).Value
        End If
    Next
Next
End Sub

这也不是检查两者是否在同一列上匹配。它检查Sheet2 的每一列与Sheet1 的每一列。我认为下面的代码就是你要找的。​​p>

Sub CopyAdjacent()
' The below line has been changed, you may still omit lastrowRemove
Dim colStatus, lastrowAdd, lastrowRemove As Integer

colStatus = 2
lastrowAdd = Sheets(“Sheet1”).Cells(Rows.Count, 1).End(xlUp).Row
' The below line is now redundant in the new code
'lastrowRemove = Sheets(“Sheet2”).Cells(Rows.Count, 1).End(xlUp).Row

For i = 1 To lastrowAdd
        If Sheets(“Sheet1”).Cells(i, 1).Value = Sheets(“Sheet2”).Cells(i, 1).Value Then
            Sheets(“Sheet2”).Cells(i, colStatus).Value = Sheets(“Sheet1”).Cells(i, colStatus).Value
        End If    
Next
End Sub

【讨论】:

  • 我明白你所做的事情的意义,我认为我已经理解了你的改变,但遗憾的是我仍然遇到同样的错误:/
  • 它是否更具体地告诉您错误发生的位置。运行时错误 9 是因为超出范围,您的工作表肯定被称为 Sheet1 和 Sheet2 还是它给了您额外的东西?还可以尝试将colStatus As Long 更改为colStatus As Integer。这可能是因为我认为你应该只用整数调用单元格引用,因为你可以拥有单元格 A1.5
  • 即使将 colStatus 从 Long 更改为 Integer,它仍然会为同一行 lastrowAdd 提供相同的调试高亮显示。另外,我的工作表被称为 Sheet1 和 Sheet2。
猜你喜欢
  • 2019-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多