简体   繁体   中英

Using Range Cells and UsedRange in for each loop

I have database extract in xlsx. I wrote a code that goes through the sheet and writes individual Cells/fields into pipe delimited text file. First, there was issue that the code ignored all rows after a row that started with "blank" value. I corrected that using UsedRange. Then, another issue began - the file has "fixed" number of columns, but sometimes, last 3 cells are blank or so. In that case, it doesnt work - it ignores blank cells at the end.

I believe that the issue is on the line with second for each loop (with myField); I spent like 5 hours googling, using help, trying different combos with Range, cells, End(xxx) and couldn't solve it. Can anyone help?

In the end, the code MUST go through the whole matrix, yet there might be blank values in first and last column.

I paste the part of code below.

    For Each myRecord In myWkSheet.Range("A1:A" & myWkSheet.UsedRange.Rows.Count)
    With myRecord
        For Each myField In myWkSheet.Range(.Cells, myWkSheet.Cells(.Row, myWkSheet.Columns.Count).End(xlToLeft))
        RplcText = myField.Text
        RplcText = Replace(RplcText, "|", "/") 'Replaces pipes from input file to slashes to avoid mismatches during ETL
        sOut = sOut & RplcText & DELIMITER
        Next myField
        OUTFILE_WRITELINE sOut
        sOut = Empty
    End With
Next myRecord`

If you have a set of header labels across the first row then put .CurrentRegion to use. see Range.CurrentRegion Property (Excel)

dim totalRows as long, totalColumns as long, dataRange as range
with sheets("sheet1").cells(1, 1).currentregion
  totalRows = .rows.count
  totalColumns = .columns.count
  set dataRange = .offset(1, 0).resize(.rows.count -1, .columns.count)  'no header row
end with

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM