[英]Using Range Cells and UsedRange in for each loop
我在xlsx中提取了數據庫。 我編寫了遍歷工作表的代碼,並將各個單元格/字段寫入到管道分隔的文本文件中。 首先,存在一個問題,該代碼忽略以“空白”值開頭的行之后的所有行。 我使用UsedRange進行了更正。 然后,另一個問題開始了-文件具有“固定”的列數,但有時最后3個單元格為空白。 在這種情況下,它不起作用-最終會忽略空白單元格。
我相信每個循環(與myField)的問題都在第二個問題上。 我花了大約5個小時來搜尋,使用幫助,使用Range,單元格,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`
如果第一行有一組標題標簽,則使用.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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.