【问题标题】:Looping through a Column in VBA to copy an entire row循环遍历VBA中的列以复制整行
【发布时间】:2016-07-21 23:06:41
【问题描述】:

我正在尝试从第 14 行开始循环遍历 K 列直到结束。我编写了以下代码,但它在 Range("K14:") 行停止工作。我尝试使用 Range("K14"& Rows.Count) 但这也无济于事。

Windows("Price VolatilityDM.xlsm").Activate
Sheets("Volatility Static Data").Activate
Dim x As Single
Dim Cell As Range
For Each Cell In Range("K14:")
    If Cell.Value > 0.25 Then
        Sheets("Volatility Static Data").Range("B:K").Copy
        Windows("Tolerance ReportDM.xslm").Activate
        Sheets("Sheet1").Range("K17:Q17").Paste
    End If
Next Cell

【问题讨论】:

  • dim lastrow as long lastrow = cells(rows.count,11).end(xlup).row For Each Cell In Range("K14:K" & lastrow )
  • OP 还没有lastrow... :)

标签: vba excel


【解决方案1】:
Windows("Price VolatilityDM.xlsm").Activate
Sheets("Volatility Static Data").Activate
Set sh = ThisWorkbook.Workheets("Volatility Static Data") ' add a reference to the sheet for simplicity
Dim x As Single
Dim Cell As Range
Dim lastRow 
lastRow = sh.Cells(sh.Rows.Count, "K").End(xlUp).Row ' get the last row
For Each Cell In Range("K14:K" & lastRow)
    If Cell.Value > 0.25 Then
        Sheets("Volatility Static Data").Range("B:K").Copy
        Windows("Tolerance ReportDM.xslm").Activate
        Sheets("Sheet1").Range("K17:Q17").Paste
    End If
Next Cell

您只需要找到Range 对象的结尾并确保您迭代到该对象。看上面;如果有任何问题,请告诉我。

【讨论】:

    【解决方案2】:

    它停在那里,因为您还没有完成整个范围的编写。 "K14:" 是无效的语法。例如,您可以这样做:"K14:K" & LastRow

    【讨论】:

      【解决方案3】:

      您可以使用类似的方法来查找从 14 开始的 K 列的结尾:

      dim end as range
      set cell = range("K14")
      
      'go down one cell at a time until you find that
      'the next one is empty. This is the end of the column
      
      do while not cell.offset(1,0).value = "" 
      
          set cell = cell.offset(1,0)
      loop
      set end = cell
      

      然后使用for each cell in range("K14:" & end.address)

      在您的代码中,它看起来像这样:

      Windows("Price VolatilityDM.xlsm").Activate
      Sheets("Volatility Static Data").Activate
      Dim x As Single
      Dim Cell As Range
      dim end as range
      
      set cell = range("K14")
      'go down one cell at a time until you find that
      'the next one is empty. This is the end of the column
      
      do while not cell.offset(1,0).value = ""   
          set cell = cell.offset(1,0)
      loop
      set end = cell
      For Each Cell In Range("K14:" & end.address)
          If Cell.Value > 0.25 Then
              Sheets("Volatility Static Data").Range("B:K").Copy
              Windows("Tolerance ReportDM.xslm").Activate
              Sheets("Sheet1").Range("K17:Q17").Paste
          End If
      Next Cell
      

      【讨论】:

        猜你喜欢
        • 2017-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-26
        • 2014-01-14
        • 1970-01-01
        • 2016-10-07
        • 1970-01-01
        相关资源
        最近更新 更多