Excel 2011 vba:如何循环列的行并将所有行乘以一个值?

Excel 2011 vba: How to loop rows of a column and multiply all rows by a single value?

我只想得到 2 列(假设它们将承载诸如 x 和 y 坐标的数字之类的值)并将列(假设)A(对于 x)中的所有值(又名行)除以某个值在 C 列中。我想对 D 列中的 B 列(对于 Y)执行相同的操作。

这就是我的进展。

(差点忘了告诉大家,proportion_height和proportion_width是H3和I3(比如1024×769)除以H4和I4(800×600)得到的。有了这些数字 H3/I3(存储在 proportion_width 中)和 H4/I4(存储在 proportion_height 中),我只需要知道如何将这两个值相乘形成 A 列到 C,从 B 列到 D。就是这样!

Sub landmarks_resizer()

' Creating variables to store the proportion of the new map. Whatever (size) it is.
Dim proportion_width As Long
Dim proportion_height As Long
Dim size_of_column As Long
Dim current_row As Long


' Just checking for NON zero values to avoid errors...
If H3 > 0 And H4 > 0 And I3 > 0 And I4 > 0 Then
    proportion_width = H3 / H4
    proportion_height = I3 / I4
End If

' Changing headers of these columns to better identify them with new values
Range("C1") = "Resized X"
Range("D1") = "Resized Y"

' Go to the very last row of column A. And from there goes Up. Which will go to the last row of column A. :-)
Range("A" & Rows.Count).End(xlUp).Select
current_row = ActiveCell.Row

With Range("H1") '<--| reference a "helper" free cell (change "H1" to your needs)
.Value = proportion_width '<--| store the dividing factor in the "helper" cell 
.Copy '<--| store the dividing factor in clipboard
End With
With Range("A1", Cells(Rows.Count, 1).End(xlUp))
.Offset(, 2).Value = .Value '<--| copy column A values to columns C
.Offset(, 2).PasteSpecial Operation:=xlPasteSpecialOperationDivide '<--| divide column C values by the value in clipboard
End With
Range("H1").ClearContents '<--| clear the content of the "helper" cell
Application.CutCopyMode = False '<--| release the clipboard

End Sub

我在这里添加了我同事的代码,我几乎成功了!每当我 运行 宏时,它都会说 '#DIV/0!'。

你可以利用 Range 对象的 PasteSpecial() 方法

这是将 A 列值除以 proportion_width 并将结果放在 C 列

中的示例
With Range("H1") '<--| reference a "helper" free cell (change "H1" to your needs)
    .Value = proportion_width '<--| store the dividing factor in the "helper" cell 
    .Copy '<--| store the dividing factor in clipboard
End With
With Range("A1", Cells(Rows.Count, 1).End(xlUp))
    .Offset(, 2).Value = .Value '<--| copy column A values to columns C
    .Offset(, 2).PasteSpecial Operation:=xlPasteSpecialOperationDivide '<--| divide column C values by the value in clipboard
End With
Range("H1").ClearContents '<--| clear the content of the "helper" cell
Application.CutCopyMode = False '<--| release the clipboard

您可以对 B 至 D 列采取类似的操作