2017-05-23 48 views
-1

此图显示了之前的版本。 https://drive.google.com/open?id=0B8BmxxuBoGYnVkhDaEF2b1J6ejA将excel中的两列进行比较,看看值是否相同

该代码的目标是查看第1列的第一个单元格的值,然后沿列向下查找第4列中的相同值。对于第1列中的第一个单元格,它将是蜂蜜,第4列中的相应行是6.然后,它将复制第5列和第6列中与第4列中的蜂蜜相对应的值,并将其放入第2列,该行中的第3列与第1列的蜂蜜相对应。每次填充第2列或第3列中的某个单元格时,它都会被标记为蓝色。我不知道如何获得正确的语法来将一个单元格中的字符串设置为与另一个单元格中的字符串相同,并确定单元格是否为空。

此图显示了后。 https://drive.google.com/open?id=0B8BmxxuBoGYnX1VXWllaQTAxWFE

Sub checkcolumns() 
'j determines the row for Column 1. n determines the row for Column 4' 
Dim j As Integer 
Dim n As Integer 
j = 1 
n = 1 

'The first part is a Do While loop and is intended to check if the first 
'cell is filled with something. If it's not then the code won't run.' 

Do While Cells(j,1).Value <> Not vbNullString 

'The next part determines whether the first cell from Column 1 and 
'first cell from Column 4 are the same. If they aren't then it will 
'search for the cell in Column 4 that has the same value. n denotes the row 
'for column 4 and the Do Until loop will determine which row in column 4 
'has the exact value as the cell we're looking at from Column 1 

    if Cell(j,1) NotEqual Cell(n, 4) 
     Do Until cell(j, 1) Equalto Cell(n, 4) 
      n = n + 1 
     End 

    'The next if statements first determine whether Column 2 of the row we're 
    'looking at has a value already. If it does not then that cell is 
    'populated with whatever value is in Column 5 of the corresponding row for 
    'Column 4 which is found with n. This is repeated for Column 3 using 
    'Column 6. 

     if Cells(j, 2).Value <> vbNullString Then 
      Cells(j, 2) = Cells(n, 5) 
      Cells(j, 2).Interior.ColorIndex = 5 
     End if 
     if Cells(j, 3).Value <> vbNullString Then 
      Cells(j, 3) = Cells(n, 6) 
      Cells(j, 3).Interior.ColorIndex = 5 
     End if 
    'This else statement below is for the case where the cell value from 
    'Column 1 on that row is equal to the cell value of Column 4 on that 
    'same row, so j and n would be equal. 
    Else 
     if Cells(j, 2).Value <> vbNullString Else 
      Cells(j, 2) = Cells(n, 5) 
      Cells(j, 2).Interior.ColorIndex = 5 
     End If 
     if Cells(j, 3).Value <> vbNullString Else 
      Cells(j, 3) = Cells(n, 6) 
      Cells(j, 3).Interior.ColorIndex = 5 
     End If 
    End If 
    'Once it has checked the first row in Column 1. It will then look at the 
    'second row. 
    j = j + 1 
End 

End Sub 
+1

使用VLOOKUP? –

+0

和条件格式的颜色? –

回答

0

将这个公式中的B2:

=VLOOKUP(A2,$D$2:$F$7,2,FALSE) 

然后把这个公式中C2:

=VLOOKUP(A2,$D$2:$F$7,3,FALSE) 

A2是要在列d $要搜索的值D $ 2:$ F $ 7创建一个静态表进行搜索 2或3是该表中的列(来自表的第一列),您要返回 False需要在搜索上完全匹配

将它们放入单元格中后,将它们向下拖动。

+0

谢谢!这非常有帮助。 –

相关问题