如何在VBA中使某些项超出范围

时间:2016-08-05 03:08:20

标签: excel vba range

我有一个大的Range,里面有13138个单元格,就像这样:

i1 <- grep("^[^D]", names(olddata)) #create an index for columns that are not D
i2 <- seq(1, ncol(olddata[i1]), by = 2)#for subsetting A, B, C
i3 <- seq(2, ncol(olddata[i1]), by = 2)# for subsetting A2, B2, C2
olddata$D2 <- c(mapply(`[`, olddata[i3], lapply(olddata[i2], `==`, olddata$D)))
olddata$D2
[1] 10 11  2 54 10  4

我需要2个“项目:”细胞之间的所有细胞分组,如

     **(A)**
   (1) Item:
   (2) HO
   (3) Item:
   (4) HO
   (5) Item:
   (6) HO
   (7) Item:
   (8) HO
   (9) Item:
   (10) MO
   (11) Item:
   (12) MFG
   (13) MO
   (14) Item:
   (15) MO
   (16) Item:
   (17) HO
   (18) Item:
   (19) MFG
   (20) MO
   (21) Item:
   (22) MFG
   (23) Item:
   (24) MFG

等等。怎么能实现这一目标?

1 个答案:

答案 0 :(得分:1)

尝试使用以下代码

Option Explicit
Sub test()
    Dim lastrow As Long, i As Long
    Dim out As String
    lastrow = Range("A" & Rows.Count).End(xlUp).Row
    For i = 1 To lastrow
        Do While Range("A" & i).Value <> "Item"
            If out = "" Then
                out = Range("A" & i).Value
            Else
                out = out & ", " & Range("A" & i).Value
            End If
            If i < lastrow Then
                i = i + 1
            Else
                Exit Do
            End If
        Loop
        Range("B" & Range("B" & Rows.Count).End(xlUp).Row + 1).Value = out
        out = ""
    Next i
End Sub

结果将在B栏中。请参阅下面的快照

enter image description here