简体   繁体   中英

Excel VBA multi cell editing using range

What the code below does is take a column of data and divides it by 100 by moving it around the spread sheet. The problem here is that there are multiple (non-consecutive) columns of data that need to be divided by 100 (for example).

LastRow = Range("K" & Rows.Count).End(xlUp).Row
Columns("K:K").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
ActiveWindow.SmallScroll Down:=18

Range("K15").Select
ActiveCell.FormulaR1C1 = "=RC[1]/100"
Range("K15").AutoFill Destination:=Range("K15:K" & LastRow)

Range("K15:K" & LastRow).Select
Selection.Copy
Range("L15").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Columns("K:K").Select

Sometimes there are consecutive columns (for example column K to N) that need to be divided by 100. (I think) the way that the code is set up, I cannot divide multiple columns of data at once...

How do I go about doing that? If there is a completely different way in coding this method so that it works for multiple cells, I am all ears (or eyes in this case)

-Jake

Use an array of the values, process the reduction then bulk load the new reduced values to the worksheet.

dim i as long, j as long, arr as variant

with worksheets("sheet1")
    arr = .range(.cells(1, "K"), .cells(.rows.count, "N").end(xlup)).value2
    for i=lbound(arr, 1) to ubound(arr, 1)
        for j=lbound(arr, 2) to ubound(arr, 2)
            arr(i, j) = cdbl(arr(i, j) / 100)
        next j
    next i
    .cells(1, "K").resize(ubound(arr, 1), ubound(arr, 2)) = arr
end with

This method assumes you were only inserting a column to help with processing; it overwrites everything in place.

you could use PasteSpecial() :

Range("A1").Copy ' say cell "A1" content is 100
Range("K1", Cells(Rows.Count, "N").End(xlUp)).PasteSpecial Paste:=xlPasteValues, Operation:=xlDivide

change Range("A1") to whatever cell you store the value to divide by in

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