VBA和传递值

时间:2017-02-07 23:00:57

标签: excel excel-vba vba

我正在尝试比较两个工作表之间的数据。每个工作表都有三列:A是客户和SKU的串联,B是销售量,C是用于衡量数量差异。我打算做两件事,检查Sheet1中不属于Sheet2的SKU,然后,如果SKU在两张纸上都匹配,请检查它们的数量差异量。如果Sheet 1的SKU不在Sheet2中,我希望突出显示该记录。我以原始的方式完成了这一点,整个行都被突出显示。但是,如果客户和我这样做,我无法获得检查卷的代码。 SKU比赛。我希望VBA保留它正在检查的单元格的值,哪里出错了,什么是正确的实现?很抱歉是这样的n00b。

Sub Again()

Dim lastRow As Integer
Dim rng As Range
lastRow = Sheets("Sheet1").Range("A65000").End(xlUp).Row

For i = 1 To lastRow
    Set rng = Sheets("sheet2").Range("A:A").Find(Sheets("Sheet1").Cells(i, 1))
    If rng Is Nothing Then
        Sheets("Sheet1").Cells(i, 3) = "Item not in sheet2"
        Sheets("Sheet1").Cells(i, 1).EntireRow.Interior.Color = vbRed
    ElseIf Not rng Is Nothing Then
        If Sheets("sheet1").Cells(i, 2).Value - Sheets("sheet2").Cells(i, 2).Value < -5 Then
            Sheets("sheet1").Cells(i, 3) = "Sheet2 reports " & Sheets("sheet1").Cells(i, 2).Value - Sheets("sheet2").Cells(i, 2).Value & " more units of volume."
        ElseIf Sheets("sheet1").Cells(i, 2) - Sheets("sheet2").Cells(i, 2) > 5 Then
            Sheets("sheet1").Cells(i, 3) = "Sheet1 reports " & Sheets("sheet1").Cells(i, 2) - Sheets("sheet2").Cells(i, 2) & " more units of volume."
        Else: Sheets("sheet1").Cells(i, 3) = "No or insignificant discrepancy"
        End If
    End If
Next

End Sub

2 个答案:

答案 0 :(得分:0)

我认为您需要像这样重复使用rng:

rng.offset(2,0).value

代替:

Sheets("sheet2").Cells(i, 2).Value

因为您当前所做的所有事情都是假设匹配的单元格与sheet1中的行完全相同。

您的代码应如下所示:

Sub Again()

Dim lastRow As Integer
Dim rng As Range
lastRow = Sheets("Sheet1").Range("A65000").End(xlUp).Row

For i = 1 To lastRow
    Set rng = Sheets("sheet2").Range("A:A").Find(Sheets("Sheet1").Cells(i, 1))
    If rng Is Nothing Then
        Sheets("Sheet1").Cells(i, 3) = "Item not in sheet2"
        Sheets("Sheet1").Cells(i, 1).EntireRow.Interior.Color = vbRed
    ElseIf Not rng Is Nothing Then
        If Sheets("sheet1").Cells(i, 2).Value - rng.offset(0, 2).Value < -5 Then
            Sheets("sheet1").Cells(i, 3) = "Sheet2 reports " & Sheets("sheet1").Cells(i, 2).Value - rng.offset(0, 2).Value & " more units of volume."
        ElseIf Sheets("sheet1").Cells(i, 2) - rng.offset(0, 2).Value > 5 Then
            Sheets("sheet1").Cells(i, 3) = "Sheet1 reports " & Sheets("sheet1").Cells(i, 2) - rng.offset(0, 2).Value & " more units of volume."
        Else: Sheets("sheet1").Cells(i, 3) = "No or insignificant discrepancy"
        End If
    End If
Next
End Sub

答案 1 :(得分:-3)

变量。 ......如果我理解你的问题。

dim myString as String dim myFloat as Float