VBA在第一个空行停止处理

我有vba生成所选列的平面文本文件。

问题是这个过程需要一段时间,因为通常是单击列字母,整个列被高亮显示,包括所有未使用的单元格。

我怎样才能让macros停止处理,当它发现第一个空行?

这是我的代码。

Sub testlist() Open "C:\Users\gaum\Desktop\Work\NCL\testlist.lst" For Output As #1 For NR = 1 To Selection.Rows.Count For NC = 1 To Selection.Columns.Count ExpData = Selection.Cells(NR, NC).Value If IsNumeric(ExpData) Then ExpData = Val(ExpData) If IsEmpty(Selection.Cells(NR, NC)) Then ExpData = "" If NC <> NumCols Then If Not ExpData = "FilePath" Then Print #1, ExpData End If Next NC Next NR Close #1 End Sub 

也是我能得到的macros产生的输出,如果我有多个select,即CTRL和左键单击各种单元格,它目前只输出第一个亮点。

非常感谢

既然你问了两个不同的问题,我将分开处理。

遇到空行时停止处理的最简单方法是在第二个For..Next循环之前添加一个检查。 问题是如何检查。 检查整个范围是否为空的最简单方法是使用CountA工作表函数。

 If WorksheetFunction.CountA(Range(NR & ":" & NR).EntireRow) = 0 Then Exit For 

上面将基本上使用工作表函数CountA并且计数在非空白范围内的单元格的数量(使用CountA在这里是重要的,因为Count工作表函数将只计数数字单元而不是非数字单元格,而CountA将计数任何东西除了空格以外,使用WorksheetFunction对象可以获得的另外一个好处是,如果只想通过指定特定Range而不是使用.EntireRow来检查几列而不是整行,则可以根据需要调整Range对象。


接下来的问题是如何处理多个选定的范围。 Selection类的另一个成员叫Areas ,它应该给你你需要的function。 Areas是一个集合,它具有您制作的每个单独select范围的范围。

您可以通过使用select的基于1的索引独立地引用每个select范围:

 NumAreaRows = Selection.Areas(1).Rows.Count 'gets the number of rows in the first selected range NumAreaCols = Selection.Areas(2).Columns.Count 'gets the number of columns in the second selected range 

所以你可以把这两个都放到你的解决scheme中:

 Sub testlist() Open "C:\Users\gaum\Desktop\Work\NCL\testlist.lst" For Output As #1 For NA = 1 To Selection.Areas.Count For NR = 1 To Selection.Areas(NA).Rows.Count If WorksheetFunction.CountA(Range(NR & ":" & NR).EntireRow) = 0 Then Exit For For NC = 1 To Selection.Areas(NA).Columns.Count ExpData = Selection.Areas(NA).Cells(NR, NC).Value If IsNumeric(ExpData) Then ExpData = Val(ExpData) If IsEmpty(Selection.Areas(NA).Cells(NR, NC)) Then ExpData = "" If NC <> NumCols Then If Not ExpData = "FilePath" Then Print #1, ExpData End If Next NC Next NR Next NA Close #1 End Sub 

CountA函数和Exit For语句在这里的放置允许您独立地循环遍历每个选定的范围,并且如果在其中一个范围中有空行,它将不会完全退出。

鉴于这个过程需要一段时间,你最好不要停留在一个空白的单元格,并删除效率低下的范围循环。 下面的代码

  • 使用variables数组而不是范围
  • 删除冗余的两步IFtesting(如果ExpData是数字,它不能也是 "FilePath"

 Sub testlist() Dim X Dim lngCnt As Long X = Selection If IsEmpty(X) Then Exit Sub Open "C:\Users\gaum\Desktop\Work\NCL\testlist.lst" For Output As #1 For lngCnt = 1 To UBound(X) If Len(X(lngCnt, 1)) = 0 Then Exit For If IsNumeric(X(lngCnt, 1)) Then Print #1, Val(X(lngCnt, 1)) Next Close #1 End Sub