【问题标题】:Return a range object using an IF statement in VBA在 VBA 中使用 IF 语句返回范围对象
【发布时间】:2016-10-19 18:25:36
【问题描述】:

我是 VBA 的初学者,正在就我的问题寻求帮助。我正在尝试执行以下操作:

  1. 遍历我的电子表格中的一列,找到对应于两个两个值组合的行
  2. 然后水平循环遍历与该组合对应的行,以返回通过 if 语句 (>40) 的所有值的范围(通过 if 语句的数字集始终是连续的,每行只有一个集合即(15、34、32、42、45、56、67、56、43、39、23、14)
  3. 我还希望能够返回通过 if 语句的第一个和最后一个值的列号,以便能够在另一行中提取日期范围

在伪代码中应该是这样的:

For r = 1 To 10000 'Loop through 10000 rows to find the correct ACV field
                If WkSht.Range("B" & r).Value = "%ACV" And WkSht.Range("C" & r) = bp_upc Then
                    'For column in row(r)
                        'If column > 40 add cell address to range object to be returned
                    'Next Column
                'End If

然后使用该范围内第一个和最后一个单元格地址的列组件来获取另一行中的值。

任何帮助或提示将不胜感激。

【问题讨论】:

    标签: vba if-statement range


    【解决方案1】:
    public sub test
      dim res as range
      dim i as long
    
      for i = 1 to 10000
        if WkSht.cells(i, 2).value = "%ACV" and WkSht.cells(i, 3) = bp_upc then
          dim numbers_range as range
          with application.intersect(WkSht.rows(i), WkSht.usedrange)
            set numbers_range = WkSht.range(WkSht.cells(i, 4), .cells(.cells.count))
          end with
    
          if res is nothing then
            set res = Get40Range(numbers_range)
          else
            dim current_res as range
            set current_res = Get40Range(numbers_range)
    
            if not current_res is nothing then set res = application.union(res, current_res)
          end if
        end if
      next
    
      'use res
      'e.g. print res.address, do res.select or loop over res.areas
    end sub
    
    private function Get40Range(byval row as range) as range
      dim c as range, start40 as range, end40 as range
    
      for each c in row
        if c.value > 40 then
          if start40 is nothing then set start40 = c
          set end40 = c
        elseif c.value <= 40 and not start40 is nothing then
          exit for
        end if
      next
    
      if end40 is nothing and not start40 is nothing then
        set end40 = row.cells(row.cells.count)
      end if
    
      if not start40 is nothing then set Get40Range = start40.resize(, end40.column - start40.column + 1)
    end function
    

    【讨论】:

    • Wowza - 对于提供的小伪代码来说,这是一个很大的工作。希望得到赞赏!
    • @GSerg 感谢您的快速回复。您提供的代码完全符合我的需要,因此非常有帮助。我不得不查找您使用的几个功能,但它开始变得有意义了。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2019-03-18
    • 2020-01-11
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多