【问题标题】:Excel VBA logic: get range between two cells using loopsExcel VBA逻辑:使用循环获取两个单元格之间的范围
【发布时间】:2016-06-08 20:19:38
【问题描述】:

请原谅,这可能很简单。我正在尝试创建一个 VBA 宏,它可以快速从原始数据中获取统计信息并将它们放在一个表中。原始数据采用以下格式:

(他们不会总是三人一组)

如何获取所有类别的范围,然后为 B 列和 C 列使用相同的范围来获取我需要的统计信息?

【问题讨论】:

  • 为什么不将类别复制到所有行中?

标签: excel vba


【解决方案1】:

下面的代码为您提供每个类别的行号,并假设 B 列的内容没有中断,您的问题是按类别获取 C:D 列的内容,拥有这些行值将使您能够编码获取 C:D 的内容。

Public Sub Sample()
Dim WkSht       As Worksheet
Dim StrCategory As String
Dim LngRow      As Long
Dim LngRowStart As Long

Set WkSht = ThisWorkbook.Worksheets("RawData")
    'Take note of the category we are one
    StrCategory = WkSht.Range("A" & 2).Value

    'Take not of the row the category started on
    LngRowStart = 2

    'Look to the next row
    LngRow = 3

    'Loop through the data until column B has no value, signifying the end of the dataset
    Do Until WkSht.Range("B" & LngRow) = ""

        'Go to the next row until we are given a new category or make it to the end of the dataset
        Do Until (WkSht.Range("A" & LngRow) <> "") Or (WkSht.Range("B" & LngRow) = "")
            LngRow = LngRow + 1
        Loop

        'Talk in the immediate pane
        Debug.Print StrCategory & " is on rows " & LngRowStart & " to " & LngRow - 1

        'Get the next values
        StrCategory = WkSht.Range("A" & LngRow)
        LngRowStart = LngRow

        'Move on
        LngRow = LngRow + 1
    Loop
Set WkSht = Nothing

End Sub

下面是我给它的输入数据:-

下面是代码的输出:-

【讨论】:

  • 这有效,但它没有更新类别名称,所以它打印出来:A 从 2 到 4.....A 从 5 到 7...A 从 8 到 10,等
  • 嗯,在您正在使用的数据中,A[blank][blank]A 不是这样吗?
  • 不,数据总会有值
  • 对不起,我的意思是 A 列,类别,在您的样本数据中,您的测试不是 A[blank][blank]A 是吗?我在答案中添加了图片,向您展示我所看到的。您将 Debug.print 更改为 MsgBox 以防万一它在即时窗口中出现奇怪的情况。
  • 原来我只是很密集(我的代码中的错字)。非常感谢您的帮助。
【解决方案2】:

您可以使用一些If 语句并将其全部放入一个数组中,但似乎只填空更直接

Sub FillColA()

    Dim LastRow As Long

    LastRow = Application.WorksheetFunction.CountA(Range("B:B"))
    Range("A2:A" & LastRow).SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C"

End Sub

【讨论】:

    猜你喜欢
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多