It is recommended that you avoid using .Select
in your code. There may be a few edge cases where you may need to use it, but the average VBA user will likely never have to encounter a single instance where they'd have to use .Select
in their lifetime.
First, we want to set the worksheet to a variable that contains the columns we are going to be looking at. Then we want to assign two separate ranges - one for the F
column and one for G
. It's easier to manage your ranges this way, and generally makes the code cleaner and easier to read.
Then sum the ranges to their own variables, and the end result would be subtracting them.
Sub TestSum()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(1)
Dim RngF As Range, RngG As Range
Set RngF = ws.Range(ws.Range("F3"), ws.Cells(lastRow(ws, "F"), "F"))
Set RngG = ws.Range(ws.Range("G3"), ws.Cells(lastRow(ws, "G"), "G"))
Dim SumF As Long, SumG As Long
SumF = Application.WorksheetFunction.Sum(RngF)
SumG = Application.WorksheetFunction.Sum(RngG)
ws.Range("G1").Value = SumF - SumG
End Sub
Function lastRow(ByVal ws As Worksheet, Optional ByVal col As Variant = 1) As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
End Function
However, you can create your own custom formula - better known as a UDF (User Defined Function). I understand you do not want the users to see the original formula, but I am not sure how you feel about one that hides everything and you simply only see the name.
Everything will be the same as above - except instead of having the Sub apply the value to the worksheet, you will assign the value to the function itself.
Function getSum() As Long
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(1)
Dim RngF As Range, RngG As Range
Set RngF = ws.Range(ws.Range("F3"), ws.Cells(lastRow(ws, "F"), "F"))
Set RngG = ws.Range(ws.Range("G3"), ws.Cells(lastRow(ws, "G"), "G"))
Dim SumF As Long, SumG As Long
SumF = Application.WorksheetFunction.Sum(RngF)
SumG = Application.WorksheetFunction.Sum(RngG)
getSum = SumF - SumG
End Function
Function lastRow(ByVal ws As Worksheet, Optional ByVal col As Variant = 1) As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
End Function
Then on your worksheet in G1
, you would type the following formula:
=getSum()
The benefit of this method is that if a value changes in either column, this would automatically update without any additional intervention.