集团的具体范围

时间:2018-01-11 14:41:16

标签: excel vba excel-vba

我正在尝试创建一个宏来选择和分组一定数量的单元格,下面是一个简单的示例图片。应该确定范围的唯一因素是column A

假设活动单元格介于row 2 and row 13之间,宏应该能够发现row 1 and row 14是该范围的边界,因为A列中存在值,因此创建和选择从row 2 till row 13开始的范围。 我试图循环遍历单元格以找到column A中具有活动值的第一行,大致了解它应该如何工作但是很难创建一个有效的代码:)

    Dim StartCell, EindCell As Range
    Dim teller As Integer
    Dim teller2 As Integer

teller = 0
Do While Selection.Offset(teller, 0).Value = ""
    teller = teller - 1
Loop
Selection.Offset(teller, 0).Select
Set StartCell = ActiveCell

teller2 = 0
Do While Selection.Offset(teller, 0).Value = ""
    teller = teller + 1
Loop
Selection.Offset(teller, 0).Select

    Set EindCell = ActiveCell
    Range(StartCell, EindCell).Select 

enter image description here

1 个答案:

答案 0 :(得分:0)

工作代码:

Sub Group()


Dim Rng As Range
Dim Rstart As Long, Rend As Long
Dim R As Long

R = ActiveCell.Row
If Len(Cells(R, "A").Value) Then R = R + 1
Rstart = R
Do Until Len(Cells(Rstart - 1, "A").Value)
    Rstart = Rstart - 1
Loop
Rend = R
R = Cells(Rows.Count, "D").End(xlUp).Row
Do Until Len(Cells(Rend + 1, "A").Value)
    Rend = Rend + 1
    If Rend = R Then Exit Do
Loop

Set Rng = Range(Cells(Rstart, "H"), Cells(Rend, "H"))

来源:

Calculating sum and grouping of dynamic range