比较excel中的两列,看看值是否相同

时间:2017-05-23 16:55:31

标签: excel excel-vba vba

此图像显示之前的图像。 https://drive.google.com/open?id=0B8BmxxuBoGYnVkhDaEF2b1J6ejA

代码的目标是查看第1列的第一个单元格的值,然后通过向下列来查找第4列中的相同值。在第1列中的第一个单元格的情况下,它将是蜂蜜,第4列中的相应行是6.然后它将复制第5列和第6列中与第4列中的蜂蜜相对应的值并将其放入第2列并且第1列中的第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 个答案:

答案 0 :(得分:0)

将此公式放在B2:

<div>

然后把这个公式放在C2中:

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

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

将它们放入牢房后,将它们向下拖动。