So as I'm ramping up a bit here, I'm also realizing how annoying it is to create an individual module for every single calculation I'm running via VBA.
I have a lot of macros similar to the following 2 below, is there a simple way to combine them into one module? Also, if I combine them, will they actually run in order (ie runs first formula, then second, third, etc..?)
Sub V1()
With ThisWorkbook.Worksheets("CT Accounts")
.Cells(4, 4).Resize(.Cells(.Rows.Count, 2).End(xlUp).Row - 1).Formula = "=IF('CT Accounts'!A4 ="""","""",IFERROR(VLOOKUP('CT Accounts'!A4,DCTM!B:B,1,0),VLOOKUP('CT Accounts'!B4,DCTM!B:B,1,0)))"
End With
End Sub
Macro number 2 .. (and honestly I have like 15-20 of these in the same workbook)
Sub V2()
With ThisWorkbook.Worksheets("CT Accounts")
With .Cells(4, 5).Resize(.Cells(.Rows.Count, 2).End(xlUp).Row - 1)
.Formula = "=IF('CT Accounts'!A4 ="""","""",VLOOKUP('CT Accounts'!A4,'Master Control'!A:R,18,0))"
.NumberFormat = "mm/dd/yy"
End With
End With
End Sub
And number 3..and on and on and on
Sub V3()
With ThisWorkbook.Worksheets("CT Accounts")
With .Cells(4, 6).Resize(.Cells(.Rows.Count, 2).End(xlUp).Row - 1)
.Formula = "=IF('CT Accounts'!A4="""","""",VLOOKUP('CT Accounts'!A4,Inactive!A:T,20,0))"
.NumberFormat = "mm/dd/yy"
End With
End With
End Sub
Do you mean like this?
Sub CombineV123()
With ThisWorkbook.Worksheets("CT Accounts")
.Cells(4, 4).Resize(.Cells(.Rows.Count, 2).End(xlUp).Row - 1).Formula = "=IF('CT Accounts'!A4 ="""","""",IFERROR(VLOOKUP('CT Accounts'!A4,DCTM!B:B,1,0),VLOOKUP('CT Accounts'!B4,DCTM!B:B,1,0)))"
With .Cells(4, 5).Resize(.Cells(.Rows.Count, 2).End(xlUp).Row - 1)
.Formula = "=IF('CT Accounts'!A4 ="""","""",VLOOKUP('CT Accounts'!A4,'Master Control'!A:R,18,0))"
.NumberFormat = "mm/dd/yy"
End With
With .Cells(4, 6).Resize(.Cells(.Rows.Count, 2).End(xlUp).Row - 1)
.Formula = "=IF('CT Accounts'!A4="""","""",VLOOKUP('CT Accounts'!A4,Inactive!A:T,20,0))"
.NumberFormat = "mm/dd/yy"
End With
End With
End Sub
You only need to do the row counting once, then you can re-use the calculated range
Sub AddAllFormulas()
Dim rng As Range
With ThisWorkbook.Worksheets("CT Accounts")
Set rng = .Rows(4).Resize(.Cells(.Rows.Count, 2).End(xlUp).Row - 1)
End With
With rng
.Columns("D").Formula = "=IF('CT Accounts'!A4 ="""","""",IFERROR(VLOOKUP('CT Accounts'!A4,DCTM!B:B,1,0),VLOOKUP('CT Accounts'!B4,DCTM!B:B,1,0)))"
With .Columns("E")
.Formula = "=IF('CT Accounts'!A4 ="""","""",VLOOKUP('CT Accounts'!A4,'Master Control'!A:R,18,0))"
.NumberFormat = "mm/dd/yy"
End With
With .Columns("F")
.Columns("F").Formula = "=IF('CT Accounts'!A4="""","""",VLOOKUP('CT Accounts'!A4,Inactive!A:T,20,0))"
.NumberFormat = "mm/dd/yy"
End With
'etc etc
End With
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.