对每个循环使用Range Cells和UsedRange

我有xlsx数据库提取。 我写了一个代码遍历工作表,并将各个单元格/字段写入pipe道分隔的文本文件。 首先,代码忽略了以“空白”值开始的行之后的所有行。 我纠正了使用UsedRange。 然后,另一个问题开始 – 文件具有“固定”的列数,但有时,最后3个单元格是空白的。 在这种情况下,它不起作用 – 它会在最后忽略空白单元格。

我相信这个问题是在每个循环的第二行(与myField); 我花了5个小时的search,使用帮助,尝试与范围,单元格,结束(xxx)不同的组合,并不能解决它。 谁能帮忙?

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

我粘贴下面的代码部分。

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` 

如果第一行有一组标题标签,则将.CurrentRegion为使用。 请参阅Range.CurrentRegion属性(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