繁体   English   中英

通过 VBA 减去:C 列中的行值 = A 列中的行值 - B 列中的行值

[英]Subtract via VBA: Rows values in Column C = Row values in Column A - Row values in Column B

我编写了一个代码,允许我在将数据粘贴到我的工作表后,将包含新数据的列动态添加到同一工作表的“每周”工作表中。 这意味着每次我每周添加数据时,我的 VBA 代码都会在“每周”表中添加一个新列,我们将其称为 ColumnC。

考虑到这些是动态的,我在这里缺少的是将 ColumnC 和 ColumnA 中包含的值减去到 ColumnB 中,也就是说,在我们需要 ColumnE - ColumnC 到 ColumnD 之后的一周:

在此处输入图片说明

有没有人可以指出正确的方向?

Sub SubtractDynamicColumns()
Dim sht As Worksheet
Dim LastColumn As Long, PreviousData As Long, PreviousColumn As Long
Set sht = ThisWorkbook.Worksheets("Weekly")

LastColumn = sht.Cells(2, sht.Columns.Count).End(xlToLeft).Column
PreviousData = sht.Cells(2, sht.Columns.Count).End(xlToLeft).Column - 2
PreviousColumn = sht.Cells(2, sht.Columns.Count).End(xlToLeft).Column - 1
End Sub

谢谢

我让这个工作,但它把值作为值,而不是作为一个公式。

Sub SubtractDynamicColumns()
Dim sht As Worksheet
Dim LastColumn As Long, PreviousData As Long, PreviousColumn As Long
Dim LastRow As Long, row_no As Long
Set sht = ThisWorkbook.Worksheets("Weekly")

 
LastColumn = sht.Cells(2, sht.Columns.Count).End(xlToLeft).Column
LastRow = ActiveSheet.Cells(Cells.Rows.Count, LastColumn).End(xlUp).Row
PreviousData = sht.Cells(2, sht.Columns.Count).End(xlToLeft).Column - 2
PreviousColumn = sht.Cells(2, sht.Columns.Count).End(xlToLeft).Column - 1

For row_no = 2 To LastRow
    sht.Cells(row_no, PreviousColumn).Value = (Cells(row_no, LastColumn).Value - Cells(row_no, PreviousData).Value)
Next


End Sub
Sub SubtractDynamicColumns()
    Dim rng As Range

    Set rng = ThisWorkbook.Worksheets("Weekly").Range("A1").CurrentRegion ' A1 - any cell in the range
    Intersect(rng.Columns(rng.Columns.Count - 1), rng.Offset(1)).FormulaR1C1 = "=RC[1]-RC[-1]" 'get the penultimate column except for the header row and set the formula
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM