如何遍历两列(找到列标题后)并计算差异?

时间:2018-02-13 15:14:44

标签: excel vba excel-vba

我正在尝试编写VBA代码来循环遍历两个单独的列,给出列名称" Market Segment"然后使用两个偏移量,第一个偏移量为Offset。(0,2),然后循环下行13行,计算与具有偏移量的列的差值。(0,6)。

我想尽可能让它变得动态,所以我想避免使用rang(A2:A15)。

example of data table

我试图循环,因为我觉得这将是最有效的方式但是因为我是VBA的新手,如果有一种更有效的方式我肯定会对此开放。

这是我编写的代码,我只是不知道如何在循环中使用它

Sub Difference() 
    Dim Sh As Worksheet 
    Dim Portfolio As Range 
    Dim MarketSeg As Range 

    For Each Sh In ThisWorkbook.Worksheets 
        With Sh.UsedRange 
            Set MarketSeg = .Cells.Find(What:="Market Segment") 
End Sub

1 个答案:

答案 0 :(得分:0)

为什么不在A列上查找“Total”的行,而不是查找Market Segment,下面的代码会这样做,并提示用户有任何区别:

Sub Difference()
    Dim Sh As Worksheet
    Dim Total As Range

    For Each Sh In ThisWorkbook.Worksheets
            Set Total = Sh.Range("A:A").Find(What:="Total", LookAt:=xlWhole)
            'look for "Total" on Column A in each Sheet
            DifferenceVal = Val(Total.Offset(0, 2)) - Val(Total.Offset(0, 6))
            'calculate difference
            MsgBox "Difference is " & DifferenceVal 'prompt user
    Next
End Sub

<强>更新

如果您想要找到“市场细分”,然后在找到“总计”行的位置偏移,则以下内容将执行此操作:

Sub Difference()
    Dim Sh As Worksheet
    Dim Total As Range
    Dim Market As Range
    Dim FirstVal As String
    Dim SecondVal As String
    For Each Sh In ThisWorkbook.Worksheets
            Set Total = Sh.Range("A:A").Find(What:="Total", LookAt:=xlWhole)
            'look for "Total" on Column A in each Sheet to find the offset value
            Set Market = Sh.Range("A:A").Find(What:="Market Segment", LookAt:=xlWhole)
            'look for "Market Segment" on Column A in each Sheet
            FirstVal = Market.Offset(Total.Row - 2, 2) 'offset by Total - 2 for headers
            SecondVal = Market.Offset(Total.Row - 2, 6)
            DifferenceVal = Val(FirstVal) - Val(SecondVal)
            'calculate difference
            MsgBox "Difference is " & DifferenceVal 'prompt user
    Next
End Sub