简体   繁体   中英

Looping through a Column in VBA to copy an entire row

I am attempting to Loop through a Column K starting at row 14 until the end. I have written the following code, but it stops working at the Range("K14:") line. I tried using Range("K14"& Rows.Count) but that didn't help either.

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
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

You just need to find the end of the Range object and make sure you iterate over to that. See above; if there are any questions, let me know.

It stops there because you haven't completed writing the whole range. "K14:" is invalid syntax. For example, you could do: "K14:K" & LastRow

you can use something like this to find the end of column K starting at 14:

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

and then use for each cell in range("K14:" & end.address)

In your code it'd look like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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