I have a piece of code that uses a select statement to SQL to generate data based on a specific date range. It works fine and does what I want. Two of those columns are what my question is about and that is F and H. F is the Payment Amount and H is the balance. G in this case is suppose to be the amount spent(which is the difference between payment amount and balance). What I'm trying to do is after the query runs and I'm given x amount of entries that if I press a button F in every row is subtracted by the corresponding H is that same row and the result goes into column G
Sub Button1_Click()
Range("G11").End(xlDown).Formula = Range("F11").End(xlDown).Value - Range("H11").End(xlDown).Value
End Sub
The SQL starts inserting the data at the 12th row hence why I have G11.End(xlDown).
Basically what I'm hoping for is something like if data is in the 12th row in F/H and is 8,3 and in the 20th row as like 13,5 than G in both the 12th and 20th row would be 5 and 9
答案 0 :(得分:0)
You can paste a single formula over a range, provided you write it with dynamic, non-fixed($) notation, so that it will use the equivalent row/column throughout such that:
dim lr as long
lr = cells(rows.count,"F").end(xlup).row 'finds the last row in column F
range(cells(12,"G"),cells(lr,"G")).formula = "=F12-H12" 'note that the formula destination and the source data start on 12
If you foresee a change from row 11, or just want to make it easier to fix later, you can do something like:
dim lr as long, r as long
r = 12 'can change this, or make in inputbox...
lr = cells(rows.count,"F").end(xlup).row 'finds the last row in column F
range(cells(r,"G"),cells(lr,"G")).formula = "=F" & r & "-H" & r
Edit1: changed all the 11s to 12s
Edit2: Will deal with the sheets problem (using the second code only, since it'll be easier to modify in the future):
With Sheets("Report")
dim lr as long, r as long
r = 12 'can change this, or make in inputbox...
lr = .cells(.rows.count,"F").end(xlup).row 'finds the last row in column F
.range(.cells(r,"G"),.cells(lr,"G")).formula = "=F" & r & "-H" & r
End With
I copy/pasted each of the codes I provided initially and verified that they work when associated with a module.