在这种情况下,我正在检查“F”范围内的每个单元格。并查看每个单元格是否与单独范围“D”中的任何单元格匹配。如果是这样,我想知道该单元格所在的行号,并将其(以及同一行的其他列中的信息)复制到另一个工作表中。如果它找不到匹配,它将打印它找不到的单元格,并在它旁边“0”。如何找到存在此数据的行的值?
Dim lastrow As Integer
lastrow = Range("F65336").End(xlUp).Row
Dim C As Integer
C = 2
For Each cell In Range("F2:F" & lastrow)
If cell.Value = Range("D2:" & lastrow) Then
sheet2.Range("B" & C).Value = Sheet1.Range("D" & C).Value
Sheet1.Range("D" & C).Value = Sheet1.Range("F" & VALUE_OF_ROW_OF_MATCHING_CELL).Value
sheet2.Range("C" & C).Value = Sheet1.Range("H" & VALUE_OF_ROW_OF_MATCHING_CELL).Value
Else
sheet2.Range("B" & C).Value = Sheet1.Range("D" & C).Value
Sheet1.Range("C" & C).Value = 0
End If
C = C + 1
Next cell
答案 0 :(得分:1)
这怎么可行?
If cell.Value = Range("D2:" & lastrow) Then
它试图将单个细胞与细胞集合进行比较,并且永远不会评估为真。
由于您提到您正在查看每个单元格是否与单独范围内的任何单元格匹配" D",我认为您的代码中每个单元格都需要另一个单元格:
Dim lastrow As Integer
lastrow = Range("F65336").End(xlUp).Row
Dim fCell, dCell
For Each fCell In Range("F2:F" & lastrow)
Dim fRow As Integer
fRow = fCell.Row
'prepopulate with default, not-found values
Sheet2.Range("B" & fRow).Value = Sheet1.Range("D" & fRow).Value
Sheet1.Range("C" & fRow).Value = 0
For Each dCell In Range("D2:D" & lastrow)
If fCell.Value = dCell.Value Then
Dim dRow As Integer
dRow = dCell.Row
Sheet2.Range("B" & fRow).Value = Sheet1.Range("D" & dRow).Value
Sheet1.Range("D" & fRow).Value = Sheet1.Range("F" & dRow).Value
Sheet2.Range("C" & fRow).Value = Sheet1.Range("H" & dRow).Value
End If
Next dCell
Next fCell
Dim lastrow As Integer
lastrow = Range("F65336").End(xlUp).Row
Dim fCell, dCell
For Each fCell In Range("F2:F" & lastrow)
Dim fRow As Integer
fRow = fCell.Row
'prepopulate with default, not-found values
Sheet2.Range("B" & fRow).Value = Sheet1.Range("D" & fRow).Value
Sheet1.Range("C" & fRow).Value = 0
For Each dCell In Range("D2:D" & lastrow)
If fCell.Value = dCell.Value Then
Dim dRow As Integer
dRow = dCell.Row
Sheet2.Range("B" & fRow).Value = Sheet1.Range("D" & dRow).Value
Sheet1.Range("D" & fRow).Value = Sheet1.Range("F" & dRow).Value
Sheet2.Range("C" & fRow).Value = Sheet1.Range("H" & dRow).Value
End If
Next dCell
Next fCell
请注意,上面假设范围跨越同一组行。如果确实如此,那么我建议使用vlookup来代替。
例如,您可以使用G列执行vlookup。把它放在G2中并填写:
然后,在Sheet2,Cell B2中,您可以参考G2:
=IFERROR(VLOOKUP(F2,D:D,1,FALSE), "")
......等等。