我的代码遍历行和列并执行操作。我想循环到第一个空列,但是, 我的代码不断循环经过此列。我的工作表当前看起来像这样:
A ---------- 1 ----------空白--------- A --------- 1
B ---------- 2 ----------空白--------- C --------- 4
C ---------- 3 ----------空白--------- W --------- 2
在上面的示例中,我想从k = 1循环到第一个空列,即k = 3(即,仅从前2列中提取数据然后停止循环)。
这是我当前的代码:
Option Explicit
Sub exitemptycolumn()
Dim lastcolumn As Long
Dim lastrow As Long
Dim sh As Worksheet
Dim rng As Range
Set sh = Sheets("sheetname")
lastcolumn = sh.Cells(1, Cells.Columns.Count).End(xlToLeft).Column
lastrow = sh.Cells(Rows.Count, 1).End(xlUp).Row
For k = 7 to lastcolumn
for j = 1 TO lastrow
set rng = sh.Range(columns(1), Columns(k))
If Application.WorksheetFunction.CountA(sh.Cells(1, k).EntireColumn) = 0 then Exit For
'rest of code
Next j
Next k
End Sub
答案 0 :(得分:2)
要回答这个问题,您想在列完全为空时结束循环。
我们可以像这样使用Application.WorksheetFunction.CountA
进行检查:
For k = 7 to lastcolumn
set rng = sh.Range(columns(1), Columns(k))
If Application.WorksheetFunction.CountA(sh.Cells(1, k).EntireColumn) = 0 then Exit For
Next k