IF Function in VBA

I managed to create a macro to show the following:

If (I3<>0,I3*G3,H3*G3) and this repeats itself for cell N3,R3, V3,Z3 ETC.

Option Explicit
Sub Eg()
Range("J3, N3,R3, V3,Z3,AD3,AH3,AL3,AP3,AT3,Ax3,BB3,XF3,BJ3").Formula = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
End Sub

Let me explain a bit more how this should work:

This report needs to be downloaded from an application.
The macro needs to be attached to this report so that when I download the report the macro automatically runs this formula in the appropriate columns.

Also I 'll have to populate the spreadhseet for all the rows with this formula.

The columns where the formula should sit are not blank but this needs to be catered for in the report automatically once the macro is run.

What am I missing here?

Hope you'll be able to help.

Thanks.

AttachmentSize
Example_Actual_Spend_on_Time_Sheet_16_11_v1.xls40.5 KB

Column J

The exisiting data in Column J should move to the next column. Then column J has the new data in. and this applies to the other columns as expalined earlier.

I need to handle variable row counts.The file will not always have 20 rows of data.

Hum, if you want to apply the

Hum, if you want to apply the formula for each column and for each row and you don't know the number of rows, you can use this subroutine instead :

Sub Eg_New()
'---------------------------------------------------------------------------
' Procedure : Eg_New
' DateTime : 16/11/2012
' Updated : 19/11/2012
' Author : Argyronet
' Purpose : Apply a formula to a set of cells
'...........................................................................
' Parameters : none

' Return Codes : none
'...........................................................................
' Notice : Press F5 to run the macro
'---------------------------------------------------------------------------
'Constants
Const CELL_COLOR As Long = 15849925
Const FIRST_ROW As Integer = 1
Const TARGET_ROW As Integer = 3

Dim oRng As Range
Dim C As Integer
Dim R As Long
Dim strRangeAddress As String
Dim intColumnIndex As Integer
Dim lngLastRow As Long

On Error GoTo L_ErrEg
'Get the working area
Cells(1, 1).Select
lngLastRow = ActiveCell.End(xlDown).Row
'For each row
For R = TARGET_ROW To lngLastRow
'For the 14 target cells (4 by 4)
For C = 10 To 62 Step 4
'Build the address A1
strRangeAddress = Cells(R, C).Address(False, False)
'Set the range object
Set oRng = Range(strRangeAddress)
'Define the range formula and its features
With oRng
.FormulaR1C1 = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
.Interior.Color = CELL_COLOR
.HorizontalAlignment = xlCenter
.Font.Bold = True
End With
Next C
Next R

On Error GoTo 0
L_ExEg:
'Hide formulas...
ActiveWindow.DisplayFormulas = False
'Freeing objects
Set oRng = Nothing
Exit Sub

L_ErrEg:
MsgBox Err.Description, 48, Err.Source
Resume L_ExEg
End Sub

It works!

Argyro

It works. However in the last column I can't see the Total Spend which is the sum of the new inserted columns.

Yes, it's true but what is

Yes, it's true but what is the formula you want to have into this column to compute then Total Spend...

The formula is

=sum(J3+N3+R3+V3+Z3+AD3+AH3+AL3+AP3+AT3+AX3+BB3+BF3+BJ3) and it will have to cater for variable row count as well.

Well, you must understand

Well, you must understand that this formula can raise circular references.
So, the subroutine must remove all colums exeed of the last one; I identified that the last column is labelled "Total Spend". Into the new script, all columns after the last are removed.
The script is the below one :
-------------------------------------------------
Sub Eg_New()
'---------------------------------------------------------------------------
' Procedure : Eg_New
' DateTime : 16/11/2012
' Updated : 19/11/2012
' Author : Argyronet
' Purpose : Apply a formula to a set of cells
'...........................................................................
' Parameters : none

' Return Codes : none
'...........................................................................
' Notice : Press F5 to run the macro
'---------------------------------------------------------------------------
'Constants
Const BILL_RATE_CELL_COLOR As Long = 15849925
Const TOTAL_SPEND_CELL_COLOR As Long = 12379352
Const FIRST_ROW As Integer = 1
Const TARGET_ROW As Integer = 3
Const BILL_RATE_FORMULA As String = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"

Dim oRng As Range
Dim C As Integer
Dim R As Long
Dim strRangeAddress As String
Dim intColumnIndex As Integer
Dim blnApplyConversion As Boolean
Dim lngLastRow As Long
Dim intLastColumn As Integer
Dim intUsedLastColumn As Integer

Dim intColPosition As Integer
Dim strTotalSpendFormula As String

On Error GoTo L_ErrEg
'Get the working area
Cells(1, 1).Select
lngLastRow = ActiveCell.End(xlDown).Row
Cells(2, 1).Select
intLastColumn = ActiveCell.End(xlToRight).Column
Cells(3, 1).Select
intUsedLastColumn = ActiveCell.SpecialCells(xlCellTypeLastCell).Column
'Delete unused columns
If intUsedLastColumn > intLastColumn Then
For C = intLastColumn + 1 To intUsedLastColumn
Columns(intLastColumn + 1).Delete
Next
End If
'For each row
For R = TARGET_ROW To lngLastRow
'For the 14 target cells (4 by 4)
For C = 10 To intLastColumn Step 4
'Build the address A1
strRangeAddress = Cells(R, C).Address(False, False)
'Set the range object
Set oRng = Range(strRangeAddress)
'Define the range formula and its features
With oRng
.FormulaR1C1 = BILL_RATE_FORMULA
.Interior.Color = BILL_RATE_CELL_COLOR
.HorizontalAlignment = xlCenter
.Font.Bold = True
End With
intColPosition = intLastColumn - C
strTotalSpendFormula = strTotalSpendFormula & "RC[-" & intColPosition & "],"
Next C
'Put the Total Spend formula
If Right$(strTotalSpendFormula, 1) = "," Then strTotalSpendFormula = Left$(strTotalSpendFormula, Len(strTotalSpendFormula) - 1)
strTotalSpendFormula = "=SUM(" & strTotalSpendFormula & ")"
'Set the range object
strRangeAddress = Cells(R, C - 1).Address(False, False)
Set oRng = Range(strRangeAddress)
With oRng
.FormulaR1C1 = strTotalSpendFormula
.Interior.Color = TOTAL_SPEND_CELL_COLOR
.HorizontalAlignment = xlRight
.Font.Bold = True
End With
strTotalSpendFormula = vbNullString
Next R
On Error GoTo 0
L_ExEg:
'Hide formulas...
ActiveWindow.DisplayFormulas = False
'Freeing objects
Set oRng = Nothing
Exit Sub

L_ErrEg:
MsgBox Err.Description, 48, Err.Source
Resume L_ExEg
End Sub

I tested

I tested it and it's missing the cell J3,N3 etc. I think it's calculating one cell after.

Also the header label Total Spend is not showing.

Will it be possible to have the macro to auto execute instead of Pressing F5?

Thanks

Hi, What do you mean by

Hi,

What do you mean by "missing the cell J3,N3" and "Total Spend is not showed"

I developed the routine from the sheet you sent to me.
In the currrent case, the process checks to the used range to eliminate unused columns and then, find the last row.
After, two loops are launched subsequently and fill the columns with the first formula. During the end of the last loop, a String creates the final formula according to existing columns and put it into the last column for each row.

For the autorun mode instead of F5, you can use the WorkbookOpen() event to execute the subroutine on the Load event.

I have atatched the file

Hi Argy

I have downloaded the file and run the macro. Please see it in attachment. you will notice that the Total Spend is not there.

Let me know if you have the file.

Thanks

Ok, I saw what you want to

Ok, I saw what you want to mean now.
Well, the script that built the total spend wasn't complete.

For AutoExec instead of F5, you can either put a command button where you attach the Eh_New() macro or you can put this subroutine that ask you to confirm when you open the workbook :
Private Sub Workbook_Open()
If MsgBox("Run the bill rate and total spend macro ?", vbQuestion + vbYesNo, "Auto compute") = vbYes Then
Eg_New
End If
End Sub

The final subroutine is this one :
Option Explicit

Sub Eg_New()
'---------------------------------------------------------------------------
' Procedure : Eg_New

' Notice : Press F5 to run the macro
'---------------------------------------------------------------------------
'Constants :

'Color for bill rate column
Const BILL_RATE_CELL_COLOR As Long = 15849925
'Color for total spend column
Const TOTAL_SPEND_CELL_COLOR As Long = 12379352
'Value of the first row (could be over 1)
Const FIRST_ROW As Integer = 1
'Row start of data (FIRST_ROW must be ajusted)
Const TARGET_ROW As Integer = 3
'Number of columns between bill rate columns
Const COLUMN_OFFSET_BETWEEN_SUBTOTALS As Integer = 3
'Bill rate formula
Const BILL_RATE_FORMULA As String = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"

Dim oRng As Range
Dim C As Integer
Dim R As Long
Dim strRangeAddress As String
Dim intColumnIndex As Integer
Dim blnApplyConversion As Boolean
Dim lngLastRow As Long
Dim intLastColumn As Integer
Dim intUsedLastColumn As Integer

Dim intColPosition As Integer
Dim strTotalSpendFormula As String

On Error GoTo L_ErrEg
Application.ScreenUpdating = False
'Get the working area
Cells(1, 1).Select
'last row
lngLastRow = ActiveCell.End(xlDown).Row
Cells(2, 1).Select
'True last column
intLastColumn = ActiveCell.End(xlToRight).Column
Cells(3, 1).Select
'Supposed last column
intUsedLastColumn = ActiveCell.SpecialCells(xlCellTypeLastCell).Column
'Delete unused columns
If intUsedLastColumn > intLastColumn Then
For C = intLastColumn + 1 To intUsedLastColumn
Columns(intLastColumn + 1).Delete
Next
End If
'For each row
For R = TARGET_ROW To lngLastRow
'For the 14 target cells (4 by 4)
For C = 10 To intLastColumn Step 4
'Build the address A1
strRangeAddress = Cells(R, C).Address(False, False)
'Set the range object
Set oRng = Range(strRangeAddress)
'Define the range formula and its features
With oRng
.FormulaR1C1 = BILL_RATE_FORMULA
.Interior.Color = BILL_RATE_CELL_COLOR
.HorizontalAlignment = xlCenter
.Font.Bold = True
End With
'Build Total Spend formula
intColPosition = intLastColumn - (C - COLUMN_OFFSET_BETWEEN_SUBTOTALS)
strTotalSpendFormula = strTotalSpendFormula & "RC[-" & intColPosition & "],"
Next C
'Put the Total Spend formula
If Right$(strTotalSpendFormula, 1) = "," Then strTotalSpendFormula = Left$(strTotalSpendFormula, Len(strTotalSpendFormula) - 1)
strTotalSpendFormula = "=SUM(" & strTotalSpendFormula & ")"
'Set the range object
strRangeAddress = Cells(R, C - 1).Address(False, False)
Set oRng = Range(strRangeAddress)
With oRng
.FormulaR1C1 = strTotalSpendFormula
.Interior.Color = TOTAL_SPEND_CELL_COLOR
.HorizontalAlignment = xlRight
.Font.Bold = True
End With
'Emptying formula variable
strTotalSpendFormula = vbNullString
Next R
'Put title
Cells(2, C - 1).Value = "Total Spend"
On Error GoTo 0
L_ExEg:
'Hide formulas...
ActiveWindow.DisplayFormulas = False
'Freeing objects
Set oRng = Nothing
Application.ScreenUpdating = True
Exit Sub

L_ErrEg:
MsgBox Err.Description, 48, Err.Source
Resume L_ExEg
End Sub

Regards...