按价值乘以整个范围?

时间:2013-09-24 19:38:31

标签: excel excel-vba vba

所以我想到的最好的方法是在很大范围内完成这个(大约450k行)是使用以下Sue-do代码:

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

现在这样可行,但我必须复制并粘贴该值这一事实似乎是多余的,因为值永远不会改变。

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

这有效,但速度较慢。因为它必须循环每个单元格。

我也尝试过:

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

但是如果列中有多个值,则收到运行时错误类型不匹配错误。

我考虑插入一个列并使用"=R-1C * 453.592"然后.Value = .Value的公式R1C1,然后移动列并覆盖,但看起来很笨拙,我认为也比粘贴倍数慢。

那么,有没有人有更好的方法来完成这项任务?

4 个答案:

答案 0 :(得分:9)

Sub Test()

    Dim rngData As Range

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

有点过时但是你在寻找什么?

答案 1 :(得分:1)

不要逐个单元格更新。它非常慢,VBA有更好的方法。这是大纲:

  1. 将范围设置为处理所需的所有行/列
  2. 将值复制到VBA中的数组
  3. 处理数组
  4. 在一次操作中将数组写回工作表
  5. 以下是一个例子:

    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
    

答案 2 :(得分:0)

我需要同样的东西。这是我如何做到的。这种方法临时使用一个单元格来存储“1”,以便与特殊粘贴相乘。

Hold = Range("A1").Formula  ' Save any existing value in A1 to Hold
Range("A1").Value = 1       ' Temporarily replace value with "1"
Range("A1").Copy            ' Copy "1" to clipboard
Columns("A:A").PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply  ' Paste multiply
Range("A1").Formula = Hold  ' Restore original A1 formula (or value, if it wasn't a formula)
Application.CutCopyMode = False  ' Clear the clipboard

答案 3 :(得分:-1)

return_sheet = ActiveSheet.Name
ActiveWorkbook.Sheets.Add
ActiveSheet.Name = "CopyPaste"
Selection.Value = 1
Selection.Copy
Sheets(return_sheet).Select 'if necessary select range you whant to multiply
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
    Application.DisplayAlerts = False
    Sheets("CopyPaste").Delete
    Application.DisplayAlerts = True
Sheets(return_sheet).Select