简体   繁体   中英

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

I wrote a code that allows me, after pasting data into my worksheet, to add a column with the new data into a table dynamically into my "Weekly" sheet of the same worksheet. This means that every single time I add data on a weekly basis, my VBA code add a new column into the "Weekly" sheet that we will call ColumnC.

What I am missing here is the subtraction of the values contained in ColumnC and ColumnA into ColumnB considering that these are dynamic, that is that the week after we will need ColumnE - ColumnC into ColumnD:

在此处输入图片说明

Is there someone who can point towards the right direction?

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

Thank you

I got this to work, but it puts the values in as values, not as a formula.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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