Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply Entire Range By Value?

Tags:

excel

vba

So The best way I could think of to accomplish this over a large range (about 450k rows) was to use the following Sue-do code:

Range("A1").Copy ' A1 Contains Value I want to multiply column by
Range("MyTable[FooColumn]").PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply

Now this works, but the fact that I have to copy and paste that value seems redundant as the value is never going to change.

For Each c In Range("MyTable[MyColumnHeader]")
    If IsNumeric(c) And Not c = "" Then
        c.Value = c.Value * 453.592 ' The value that is in A1 from previos sample
    End If
Next

That works, but is slower. As it has to loop every cell.

I also tried:

With Range("MyTable[MyColumnHeader]")
    .Value = .Value * 453.592
End With

But received runtime error Type Mismatch Error if there was more then one value in the column.

I thought about inserting a column and using the formulaR1C1 of "=R-1C * 453.592" Then .Value = .Value, Then shift the column and overwrite but seemed clunky and I would think also slower then the paste multiply.

So, does anyone have any better ways of accomplishing this task?

like image 785
user2140261 Avatar asked Sep 24 '13 19:09

user2140261


People also ask

How do I multiply an entire range in Excel?

Right click the selected range and select Paste Special. Then select Multiply and click OK. Now all the cells in the range will have *(Factor) added to their formula. You can change the value in the cell named Factor and the other cells' values will change.


2 Answers

Sub Test()

    Dim rngData As Range

    Set rngData = ThisWorkbook.Worksheets("Sheet1").Range("A1:B10")
    rngData = Evaluate(rngData.Address & "*2")
End Sub

Kind of outdated but is that what you were looking for ?

like image 193
user2359459 Avatar answered Oct 25 '22 01:10

user2359459


Do not update cell by cell. It is very slow and there is a better way with VBA. Here is the outline:

  1. Set a Range to all rows/columns needed to process
  2. Copy values into array in VBA
  3. Process the array
  4. Write the array back into the worksheet in one operation

Here is an example:

Public Sub FactorRange(ByRef r_first as Range, ByVal N_rows as Long, _
ByVal N_cols as Long, ByVal factor as Double)
    Dim r as Range
    'Set range from first cell and size
    Set r = f_first.Resize(N_rows,N_cols)
    Dim vals() as Variant
    ' Copy cell values into array
    vals = r.Value
    Dim i as Long, j as Long
    ' Do the math
    For i=1 to N_rows
      For j=1 to N_cols
        vals(i,j) = factor * vals(i,j)
      Next j
    Next i
    ' Write values back
    r.Value = vals
End Sub
like image 36
John Alexiou Avatar answered Oct 24 '22 23:10

John Alexiou