|
|
递归搜寻、扩展当前区域的 功能模拟代码:
- Dim r&, c&, i1&, i2&, j1&, j2&
- Sub test()
- r = Rows.Count: c = Columns.Count
- i1 = ActiveCell.Row: i2 = i1
- j1 = ActiveCell.Column: j2 = j1
- Call CurR
- Range(Cells(i1, j1), Cells(i2, j2)).Select
- End Sub
- Sub CurR()
- t = False: t2 = False
-
- Do While j1 > 1 'left
- j = j1 - 1
- For i = IIf(i1 = 1, 1, i1 - 1) To IIf(i2 = r, r, i2 + 1)
- If Cells(i, j) <> "" Then j1 = j: t = True: Exit For
- Next
- If t Then t = False: t2 = True Else Exit Do
- Loop
- Do While j2 < c 'right
- j = j2 + 1
- For i = IIf(i1 = 1, 1, i1 - 1) To IIf(i2 = r, r, i2 + 1)
- If Cells(i, j) <> "" Then j2 = j: t = True: Exit For
- Next
- If t Then t = False: t2 = True Else Exit Do
- Loop
-
-
- Do While i1 > 1 'up
- i = i1 - 1
- For j = IIf(j1 = 1, 1, j1 - 1) To IIf(j2 = c, c, j2 + 1)
- If Cells(i, j) <> "" Then i1 = i: t = True: Exit For
- Next
- If t Then t = False: t2 = True Else Exit Do
- Loop
- Do While i2 < r 'down
- i = i2 + 1
- For j = IIf(j1 = 1, 1, j1 - 1) To IIf(j2 = c, c, j2 + 1)
- If Cells(i, j) <> "" Then i2 = i: t = True: Exit For
- Next
- If t Then t = False: t2 = True Else Exit Do
- Loop
-
- ' Range(Cells(i1, j1), Cells(i2, j2)).Select
- If t2 Then Call CurR
- End Sub
复制代码
算法原理:
从当前位置开始,向左、向右、向上、向下,搜寻更外侧的行/列区域内是否有非空单元格。
有就扩展当前的行/列,没有就不变。
继续递归此过程,直至所有的左右上下方向都没有能够扩展时停止。
|
|