VBA树/层次结构

时间:2013-07-18 16:05:15

标签: vba tree hierarchy

我正在尝试使用Excel填写我所拥有的组织层次结构中的空白单元格。以下场景之前和之后。

我尝试过伪代码。

before

After

For all rows
For all cells in row
If cell is populated, row++
If cell is not populated, copy the value immediately above to the current cell and check next cell in row.
  1. 这个逻辑是否合理?
  2. 我将如何在VBA中实现此功能?
  3. 我猜我可以像这样迭代每行中的每个单元格......

    For Each row In rng.Rows
    For Each cell in row.Cells
    'Do Something
    Next cell
    Next row
    

    然后我卡住了!任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

你的逻辑是合理的。尝试这样的事情:

Sub FillTree()
Dim rng as Range
Dim r as Range
Dim c as Range
Dim cl as Range

Set rng = Range("A1:E50") '## Modify this to the full range you want to fill in.

For Each r In rng.Rows                     '# iterate over each column
    For Each cl in r.Cells                 '# check each cell in the column
        If Trim(cl) = vbNullString Then    '# if the cell is empty, fill from above
            cl = cl.Offset(-1,0)
        Else:                              '# skip to the next row if populated
            Exit For
        End If
    Next
Next 

End Sub