Reputation: 671
I am trying to loop a formula instead of using filldown
because i have two formulas depending on the length of text in Column A's Cell.
my two formulas are like
.Range("C2").Formula = "=CHAR(83)&CHAR(45)&LEFT(A2,LEN(A2)-9)&CHAR(45)&UPPER(MID(A2,4,LEN(A2)-8))&CHAR(32)&D2&E2"
.Range("C2").Formula = "=LEFT(A2,LEN(A2)-9)&CHAR(45)&UPPER(MID(A2,8,LEN(A2)-12))&CHAR(32)&D2&E2"
This is what i have so far.
Sub AddFormulas()
Application.ScreenUpdating = False
Dim aCell As String
Dim cCell As String
Dim dCell As String
Dim eCell As String
Dim rowStart As Integer
Dim aCol As Integer
Dim cCol As Integer
Dim dCol As Integer
Dim eCol As Integer
Dim LastRow As Long
LastRow = Range("A" & Rows.Count).End(xlUp).Row
rowStart = 2
aCol = 1
cCol = 3
dCol = 4
eCol = 5
'Range("A2")
aCell = Cells(rowStart, aCol).Address(RowAbsolute:=False, _
ColumnAbsolute:=False)
'Range("C2")
aCell = Cells(rowStart, cCol).Address(RowAbsolute:=False, _
ColumnAbsolute:=False)
'Range("D2")
dCell = Cells(rowStart, dCol).Address(RowAbsolute:=False, _
ColumnAbsolute:=False)
'Range("E2")
eCell = Cells(rowStart, eCol).Address(RowAbsolute:=False, _
ColumnAbsolute:=False)
With ThisWorkbook.Sheets("Sheet1")
.Range(cCell).Formula = "=CHAR(83)&CHAR(45)&LEFT(aCell,LEN(aCell)-9)&CHAR(45)&UPPER(MID(aCell,4,LEN(aCell)-8))&CHAR(32)&(dCell)&(eCell)"
End With
Application.ScreenUpdating = True
End Sub
Thx
Upvotes: 0
Views: 1124
Reputation: 6186
You haven't explained the number of chars to determine which formula to use, you can use an IF statement to determine the char length of a cell using LEN
Then you can post your formula with just one line of code to the entire range as Excel is smart enough to increment by row. Here is an example:
Range("B1:B" & Range("A" & Rows.Count).End(xlUp).Row).Formula = "=IF(LEN(A1)=2,123,987)"
This will put 123 in column B where the corresponding row in column A has a length of 2 characters otherwise it will enter 987.
Change the LEN(A1)=2
to the length to trigger the first formula, change 123 to the first formula and change 987 to the second formula you want. If you are testing any cell other than column A, also change that in the LEN
part of the formula.
Lastly, why on earth are you making this so complex? Why do CHAR(83)&CHAR(45)
instead of "S-"
its going to be harder to maintain if you put everything in by it's ASCII code.
Upvotes: 1