Excel VBA从另一列中减去一列,但不在单元格中

Sub TryAgain() Dim A As Range '~ I will put the result in this column, A Dim B As Range Dim C As Range '~ [BC] is the what I need Dim onecell As Range Dim twocell As Range Set B = Range("C2", Range("C2").End(xlDown)) 'log prices of Z over time Set C = Range("D2", Range("D2").End(xlDown)) 'log prices of WPC over time Set A(1) = B.Value - C.Value End Sub 

我一直在努力解决这个烦人的问题一段时间。

这是两列之间的SIMPLE减法操作,

所以我想要做的是进行减法操作“CELL-BY-CELL”

但! 我不想把结果放在单元格中(被引用)或创build任何其他表单。

所以,我想直接将减法结果(即C2-D2,C3-D3 …)分配给一个名为A的variables(这应该是一列),
不要在工作表单元格上logging和引用单元格 ,但是这显然很难通过。

有没有其他方法可以做到这一点?

非常感谢提前!

我想你正在寻找一个数组

 Sub TryAgain() Dim A() As Integer '~ I will put the result in this column, A Dim i As Integer Dim lastrow As Integer lastrow = Range("B2").End(xlDown).Row '<- assume there's no empty cells from C2 to last row on column C ReDim A(lastrow) For i = 1 To lastrow A(i) = Cells(i + 1, 2).Value - Cells(i + 1, 3).Value Next ' add below for loop to print out result For j = 1 To lastrow - 1 Debug.Print A(j) Next End Sub 

以下是基于您所描述的示例电子表格:

示例电子表格

而这个代码将解决问题…显示它的工作有一个循环在最后的消息框来显示答案,但你可以使用代码中所示的数组 ,如您所计划的。 我想你可能想考虑将数据存储在一个范围内的好处,但这是你的deviseselect。

 Sub SubtractCells() Dim dblTolerance As Double Dim tmp As Range Dim A() As Double Dim intListSize As Integer Dim i As Integer 'Get source range Set tmp = ActiveSheet.Range("C2") 'Get size of list by finding last row Do Until tmp.Offset(1, 0).Value = "" Set tmp = tmp.Offset(1, 0) Loop 'Subtract last row from first row of data to get number of rows and add one for offset from beginning intListSize = (tmp.Row - 2) + 1 ReDim A(intListSize) i = 1 'index for array 'use the temporary variable to cycle through the range Set tmp = ActiveSheet.Range("C2") Do Until tmp.Value = "" 'Subtract the two rows and store in array A(i) = tmp.Value - tmp.Offset(0, 1).Value 'Update range row and index i = i + 1 Set tmp = tmp.Offset(1, 0) Loop 'Loop through array to see results 'This is only to verify code works comment out and use array 'I would rethink storing this on a spreadsheet. For i = 1 To intListSize MsgBox ("A(" & Str(i) & "):" & Str(A(i))) Next 'Clean up Set tmp = Nothing End Sub 

如果您有任何问题,请告诉我。