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

时间:2017-02-20 03:46:32

标签: excel vba excel-vba excel-2011

我只想获得2列(想象它们将托管诸如x和y坐标的数字之类的值)并将所有值(也就是说行)从列(比方说)A(对于x)除以特定值C列。我想对D列中的B列(Y)做同样的事情。

这是我有多远。

(几乎忘了告诉你们,比例_高度和比例宽度是通过H4和I4(800 x 600)划分H3和I3(例如1024 x 769)获得的。具有这些数字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!'。

1 个答案:

答案 0 :(得分:1)

您可以利用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

的行为类似