Excel VBA不等于不起作用

时间:2016-03-23 10:44:04

标签: excel vba if-statement

您好在另一个论坛上发现了一个解决了我的问题的宏:它复制了Sheet 2中匹配Sheet 1的单元格。

Sub Compare()

Dim WS As Worksheet
Set WS = Sheets("Master")

Dim RowsMaster As Integer, Rows2 As Integer
Dim Rows3 As Integer
RowsMaster = WS.Cells(1048576, 1).End(xlUp).Row
Rows2 = Worksheets(2).Cells(1048576, 1).End(xlUp).Row
Rows3 = WS.Cells(WS.Rows.Count, 1).End(xlUp).Row
' Get the number of used rows for each sheet
ScreenUpdating = False
With Worksheets(2)
    For i = 2 To Rows2
    ' Loop through Sheet 2
        For j = 2 To RowsMaster
        ' Loop through the Master sheet
            'below line checks for matches to variable number, file and field
            If .Cells(i, 1) = WS.Cells(j, 1) And .Cells(i, 3) = WS.Cells(j, 3) And .Cells(i, 4) = WS.Cells(j, 4) Then
            ' If a match is found:
                WS.Cells(j, 6) = .Cells(i, 1)
                  WS.Cells(j, 7) = .Cells(i, 2)
                    WS.Cells(j, 8) = .Cells(i, 3)
                      WS.Cells(j, 9) = .Cells(i, 4)

                ' above copies in the data
                 Exit For
                ' No point in continuing the search for that company

            ElseIf j = RowsMaster Then
            ' If we got to the end of the Master sheet
            ' and haven't found a company match

                Rows3 = Rows3 + 1
                ' Increment the number of rows
                For k = 1 To 4
                'For l = 2 To 4 ' Change 3 to however many fields Sheet2 has

                    WS.Cells(Rows3, 11) = .Cells(i, k)
                    ' Copy the data from Sheet2 in on the bottom row of Master
                Next
            End If

        Next j
    Next i
End With
ScreenUpdating = True
End Sub

此代码将sheet2中的值与master匹配。不匹配的那些只在单元格K6中结束 - 我需要的是完成匹配的那些在K列中开始(日期K:N的4列)然后每一行在新行上。

任何人都可以帮我解决这个问题 - 已经工作了2天而且无法正常工作!

感谢。

0 个答案:

没有答案