测试VBA中的单元格是否为空

时间:2013-05-24 11:23:37

标签: vba while-loop is-empty

我正在尝试在VBA中编写一个模块,以获取包含网站结构的工作表,并将工作表输出到两列中,其中列(第1列)是页面名称,(第2列)部分是页面所在的站点。(所以我可以在Visio中使用它)

我现有的工作表包含如下结构:

Root / Section / Sub-section / Page
Root / Section / Page
Root / Section / Sub-section / Sub-section / Page

即。每一行都在左侧列中显示页面的祖先,但结构有不同的级别使问题复杂化。

我正在尝试遍历这一点,从第7列(最深层次的导航)开始,最初向左循环以找到非空单元格,然后将该单元格及其父级复制到我的新工作表中。一旦它到达第2列,我希望它向下移动,因为它包含根;这一直持续到562的最后一行。

我的代码在下面,但它在我的'While Isempty'行上给了我一个错误。我做错了什么?

Sub directDescendent()

Dim readCol As Integer
Dim readRow As Integer
Dim writeRow As Integer
readCol = 7
readRow = 2
writeRow = 2

While readRow < 562
    While IsEmpty(ActiveWorkbook.Sheets(2).Cells(readRow, readCol).Value)
        readCol = readCol - 1
    Wend
    If readCol < 3 Then
        readCol = 7
        readRow = readRow + 1
    End If
    ActiveWorkbook.Sheets(3).Cells(writeRow, 1).Value =     ActiveWorkbook.Sheets(2).Cells(readRow, readCol).Value
    ActiveWorkbook.Sheets(3).Cells(writeRow, 2).Value = ActiveWorkbook.Sheets(2).Cells(readRow, readCol - 1).Value
    writeRow = writeRow + 1

Wend
End Sub

2 个答案:

答案 0 :(得分:3)

当代码第7次输入readCol时,While IsEmpty(ActiveWo...变量的值为0(零)(最小值应为1)因此当索引超出范围时抛出异常(要求具有元素1 to n

的东西的第0个元素

答案 1 :(得分:1)

您可以使用for-next with step = -1。虽然迭代的数量是已知的(7),但是并不是必需的。

For readCol = 7 To 1 Step -1
    If Not IsEmpty(ActiveWorkbook.Sheets(2).Cells(readRow, readCol).Value) Then Exit For
Next readCol

'
' Note:
' Here readCol would be equeal to zero if all cells from column 7 to 1 are empty.
' 
相关问题