简体   繁体   中英

How to copy the values within a dynamic named range?

I've doing a waste calculation exercise at work, and I've got several dynamic named ranges whose cells all contain values arrived at by formulae. I need a module that will copy the values within a dynamic named range onto another sheet without copying the formulae themselves, just the values that the cells contain. I tried to use this:

Sub Sample()
    Dim wsI As Worksheet, wsO As Worksheet

    Set wsI = ThisWorkbook.Sheets("Sheet1")
    Set wsO = ThisWorkbook.Sheets("Sheet1")

    wsI.Range("Pct_waste").Copy wsO.Range("B4")

End Sub

But this copies the formulae, which is no use. And I can't just use absolute references because I need to be able to quickly add new data. Ultimately, I intend to create a macro that will copy the values within the dynamic named ranges to a new sheet, then sort these values numerically and plot them on a scatter chart. So I need to find a way to copy all the values in my dynamic named ranges without copying the formulae themselves.

Also, I'm fairly novice when it comes to VBA so go easy!

Use the .Resize() method:

Set wsI = ThisWorkbook.Sheets("Sheet1")
Set wsO = ThisWorkbook.Sheets("Sheet1")

With wsI.Range("Pct_waste")
    wsO.Range("B4").Resize(.Rows.Count, .Columns.Count).Value = .Value
End With

Try pasting the value only:

Sub Sample() 

Dim wsI As Worksheet, wsO As Worksheet

Set wsI = ThisWorkbook.Sheets("Sheet1")
Set wsO = ThisWorkbook.Sheets("Sheet1")

wsI.Range("Pct_waste").Copy 
wsO.Range("B4").PasteSpecial xlPasteValues

End Sub

or something like this

Sub test()

Dim r As Excel.Range
Dim i As Integer

Set r = Range("test_range")

For i = 1 To r.Cells.Count
    Range("x" & i).Value = r.Cells(i, 1).Value
Next i

End Sub

or you could do something like this as static formula in the sheet, =index(range_name,rows($A$1:$A1),1) and fill down, also trap the errors using IFERRROR, this will be static though.

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