如何选择从第一个非黑色到最后一个非空白单元格(VBA)的单元格范围?

时间:2016-05-23 11:40:17

标签: excel vba excel-vba export visual-studio-macros

我正在尝试将表从excel工作簿导出到管道分隔的txt文件,这些文件的命名方式与相应的工作表相同。问题是我无法让我的宏遍历工作簿中的不同工作表以将所有非空单元格导出到txt文件。以下是我的代码:

Sub TableExtract()

Dim myFile As String, WS_Count As Integer, x As Integer, rng As Range, cellValue As Variant, i As Integer, j As Integer

WS_Count = ActiveWorkbook.Worksheets.Count
For x = 1 To WS_Count

    myFile = "C:\Users\mohamednuri.beitelma\Desktop\" & ActiveSheet.Name & ".txt"

    Set rng = Sheets(x).Range("A1").CurrentRegion
    Open myFile For Output As #1

    For i = 1 To rng.Rows.Count
        For j = 1 To rng.Columns.Count

            cellValue = rng.Cells(i, j).Value

            If j = rng.Columns.Count Then
                Print #1, cellValue
            Else
                Print #1, cellValue & "|",
            End If

            Next j
        Next i
    Close #1
Next x

End Sub

此代码返回错误。知道如何在第一个和最后一个非空白单元格之间的范围内选择内容并导出它吗?

1 个答案:

答案 0 :(得分:0)

使用当前的region属性:

Set rng = Range("A1").CurrentRegion

这是选择A1的等值,按 Ctrl + A

您的错误是由于您为Range方法分配行号和列号而导致的,您应该有一个地址或开始/结束单元格:

'// lets assume row = 5
row = Range("A" & Rows.Count).End(xlUp).row

'// lets assume col = 10
col = Cells(1, Cells.Columns.Count).End(xlToLeft).Column

'// this will produce Range(5, 10) <~~ invalid syntax
Range(row, col).Select

'// consider instead:
Set rng = Range(Cells(1, 1), Cells(row, col))
'// or use the .CurrentRegion property as mentioned above if there are no gaps in your data.