在每个循环中使用 Range Cells 和 UsedRange

Using Range Cells and UsedRange in for each loop

我在 xlsx 中有数据库提取。我编写了一个代码,它通过 sheet 并将单个 Cells/fields 写入管道分隔的文本文件。首先,存在代码忽略以 "blank" 值开头的行之后的所有行的问题。我使用 UsedRange 更正了这一点。然后,另一个问题开始了——文件有 "fixed" 列,但有时,最后 3 个单元格左右为空。在那种情况下,它不起作用 - 它会忽略末尾的空白单元格。

我认为问题出在每个循环的第二个(使用 myField);我花了大约 5 个小时在谷歌上搜索,使用帮助,尝试使用 Range、cells、End(xxx) 的不同组合,但无法解决它。谁能帮忙?

最后,代码必须遍历整个矩阵,但第一列和最后一列可能有空白值。

我粘贴下面的部分代码。

    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`

如果第一行有一组 header 个标签,则使用 .CurrentRegion。见 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