如何在VBA中以更简单的方式解决调试此问题

时间:2019-04-14 15:23:12

标签: excel vba

在A列中,我有一系列不同的值。喜欢:

CA_ALAMEDA
CA_ALPINE
OR_LANE

,依此类推。大约300行。

对于每一行,在E列中,我有1到85个值之间的任意值,以逗号分隔,例如:

SAN LEANDRO,HAYWARD,ALBANY,ALAMEDA
BEAR VALLEY,LAKE ALPINE,KIRKWOOD,MESA VISTA,MARKLEEVILLE,WOODFORDS,FREDRICKSBURG,CRYSTAL SPRINGS
EUGENE,SPRINGFIELD

我需要对宏做的是

  1. 在每个现有行之间插入一定数量的行,等于E列中单元格中的逗号数。我已经确定了逗号数并将该值放在B列中。第一行显示:CA_ALAMEDA. . . 3. . . <column c=""> . . . <column d=""> . . . SAN LEANDRO,HAYWARD,ALBANY,ALAMEDA

  2. 用E列中的各个值填充新行中的单元格。我将它们放在C列中。因此,最终结果将如下所示: CA_ALAMEDA . . . 3 . . . SAN LEANDRO . . . <column d=""> . . . SAN LEANDRO,HAYWARD,ALBANY,ALAMEDA . . . . . . . . . . . . . . . . . . HAYWARD . . . . . . . . . . . . . . . . . . ALBANY . . . . . . . . . . . . . . . . . . ALAMEDA CA_ALPINE. . . . . .7 . . . BEAR VALLEY . . . . <column d=""> . . . BEAR VALLEY,LAKE ALPINE,KIRKWOOD,MESA VISTA,MARKLEEVILLE,WOODFORDS,FREDRICKSBURG,CRYSTAL SPRINGS . . . . . . . . . . . . . . . . . . LAKE ALPINE . . . . . . . . . . . . . . . . . . KIRKWOOD

1 个答案:

答案 0 :(得分:0)

可以尝试类似的操作(如果我正确理解了这个问题)

Sub test()
Dim Ws As Worksheet, StrS As Variant, SubNameCnt As Long
Dim Rw As Long
Set Ws = ThisWorkbook.Sheets("Sheet2")
Rw = 1
nm = Ws.Range("A" & Rw).Value
    Do While nm <> ""
    StrS = Split(Ws.Range("E" & Rw).Value, ",")
    SubNameCnt = UBound(StrS) + 1

        'Somehow speedy than single row insert
        If SubNameCnt > 0 Then
        Ws.Range("A" & Rw + 1 & ":A" & Rw + SubNameCnt).EntireRow.Insert xlShiftDown
        Ws.Range("A" & Rw + 1 & ":A" & Rw + SubNameCnt).Value = nm
        Ws.Range("C" & Rw + 1 & ":C" & Rw + SubNameCnt).Value = Application.Transpose(StrS)
        End If

        'A slow process (so not used but produced for simple understanding only)
        'For i = LBound(StrS) To UBound(StrS)
        'Ws.Range("A" & Rw).Offset(i + 1).EntireRow.Insert xlShiftDown
        'Ws.Range("A" & Rw).Offset(i + 1).Value = nm
        'Ws.Range("A" & Rw).Offset(i + 1, 1).Value = i + 1
        'Ws.Range("A" & Rw).Offset(i + 1, 2).Value = StrS(i)
        'Next i

    Rw = Rw + SubNameCnt + 1
    nm = Ws.Range("A" & Rw).Value
    Loop
End Sub

使用临时数据测试代码