简体   繁体   English

在每个循环中使用范围单元格和UsedRange

[英]Using Range Cells and UsedRange in for each loop

I have database extract in xlsx. 我在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. 我使用UsedRange进行了更正。 Then, another issue began - the file has "fixed" number of columns, but sometimes, last 3 cells are blank or so. 然后,另一个问题开始了-文件具有“固定”的列数,但有时最后3个单元格为空白。 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); 我相信每个循环(与myField)的问题都在第二个问题上。 I spent like 5 hours googling, using help, trying different combos with Range, cells, End(xxx) and couldn't solve it. 我花了大约5个小时来搜寻,使用帮助,使用Range,单元格,End(xxx)尝试不同的组合,但无法解决。 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. 如果第一行有一组标题标签,则使用.CurrentRegion see Range.CurrentRegion Property (Excel) 请参见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.

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