vbaexcelexportvisual-studio-macros

How to select range of cells, from first non-black to last non-blank cell (VBA)?


I am attempting to export tables from excel workbooks to pipe-delimited txt files which are named in the same manner as the corresponding sheet. The issue is that I am not able to get my macros to iterate through the different sheets in a workbook to export all the non-blank cells to a txt file. Below is my code:

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

This code returns an error. Any idea how I can select al lthe content in the range between the first and last non-blank cells, and export it?


Solution

  • Use the current region property:

    Set rng = Range("A1").CurrentRegion
    

    This is the equivelant of selection A1 and pressing Ctrl + A


    Your error is being caused because you're assigning a row number and a column number to the Range method, where you should have an address or a start/end cells:

    '// 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.