如何使用Match函数并引用它返回的行号?

时间:2018-07-17 15:10:23

标签: excel vba filter subtraction

我会尽力解释这一点。我正在处理一个包含大约150列和2500行的电子表格。在D列中,存在该行唯一的标识号。我需要在该列上过滤特定的ID号(例如B5555),然后从该行的AB,O和M列中的值减去该行AH列中的值。然后我需要将AH列中的值清零。

过滤ID号没有问题,但是B5555可以显示在任何行中。 IE,一周显示在2,300行中,下一周显示在1,500行中,所以我不能仅使公式说从AB 2300中减去AH2300,因为下周将对错误的单元格起作用。如何使公式特别从B5555出现的行中减去?到目前为止,我的代码只过滤该ID号,所以它虽然不多,但如下所示。我是VBA的新手,不胜感激。

Sub ManualAdjustments()

Dim wbTarget            As Workbook
Dim wbThis              As Workbook
Dim strName             As String
Dim rownum              As Integer

Set wbTarget = Workbooks("Weekly Data")

wbTarget.Activate

Worksheets("Raw").Activate

rownum = Application.WorksheetFunction.Match("B5555", 
Sheets("Raw").Range("D:D"), 0)

以上代码是我到目前为止所拥有的。如何在简单的减法公式中引用“ rownum”?会是:Worksheets(“ Raw”)。Range(“ AHrownum”)-Worksheets(“ Raw”)。Range(“ ABrownum”)

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

Sub ManualAdjustments()
Dim rownum As Long
Dim ws As Worksheet: Set ws = Worksheets("Raw")

'Get the row number where value "B5555" is found in Column D
rownum = ws.Range("D:D").Find(What:="B5555", Lookat:=xlWhole).Row

'Subtract AH minus AB, O & M
NewValue = ws.Range("AH" & rownum) - ws.Range("AB" & rownum) - ws.Range("O" & rownum) - ws.Range("M" & rownum)

MsgBox "Your New Value is: " & NewValue
End Sub

答案 1 :(得分:0)

稍有不同的方法:

Sub ManualAdjustments()

    Dim wbTarget            As Workbook
    Dim shtTarget           As Worksheet
    Dim wbThis              As Workbook
    Dim strName             As String
    Dim rownum              As Long '<<< safer never to use Integer...

    Set wbTarget = Workbooks("Weekly Data")
    Set shtTarget = wbTarget.Sheets("Raw")

   'no "worksheetfunction" = no runtime error if no match
    rownum = Application.Match("B5555", shtTarget.Range("D:D"), 0)

    If Not IsError(rowNum) Then '<< test for successful match here
        With shtTarget.Rows(rownum) 

            'Here Range() is *relative to the row*
            .Range("C1").Value = .Range("A1").value = .Range("B1").Value

        End With

    End if
End Sub