VBA/Excel If...Then...ElseIf...Else Statement copy down column issue - excel

Okay, I have the statement figured out, it works just how I need it to. When I run it, it pretty much looks for the Interior.Color and if it matches it gives me the Text value of said cell color. How do I copy and paste this If Statement down the entire column as long as there's data?
I do not know the VBA version for this. So the VBA Code I have looks like this:
If Range("F2").Interior.Color = 255 Then
Range("AE2") = "Red"
ElseIf Range("F2").Interior.Color = 65252 Then
Range("AE2") = "Green"
Else
Range("AE2") = "New"
End If
I want that entire statement to be copied down column AE until there's no data in column F (Copy/Paste) but it changes accordingly, and follows the cells down.
Hopefully I'm making sense.
Thank you

since you didn't mention which Column holds data, I assumed it's Column F, you can modify the code easily according to your needs.
I also switched your IFs to Select Case, if in the future you will have more conditions to test.
' assuming your column that has data is Column F >> modify it according to your needed column
lastRow = Cells(Rows.count, "F").End(xlUp).row
For lRow = 2 To lastRow
Select Case Range("F" & lRow).Interior.Color
Case 255
Range("AE" & lRow) = "Red"
Case 65252
Range("AE" & lRow) = "Red"
Case Else
Range("AE" & lRow) = "New"
End Select
Next lRow

Related

Having fits with a formula which includes a variable

I have been trying to put a SUMIF formula into a cell but it returns a weird result.
BottomRow winds up being the last row in a table. When I run the macro and look at the value of txtformula in the immediate window I get =Sumif(B6:B241,F6:F19,D6:D241)
when it goes in the cell it enters =SUMIF(B6:B241,#F6:F19,D6:D241)
Where is the darn # sign coming from?
Range("B6").End(xlDown).Select
Classbottom = ActiveCell.Address
BottomRow = Range(Classbottom).Row
'Create totals data
Range("G6").Activate
txtFormula = "=Sumif(B6:B" & BottomRow & ",F6:F19,D6:D" & BottomRow & ")"
ActiveCell.Formula = txtFormula
I guessed at trying a different formula. I did
activecell.formula2 = txtFormula
It did the trick

Why is my VBA code applying formula to all rows under a column?

I want to apply a formula only to rows that satisfy a condition, but it is somehow applying the formula to all rows.
I have an Excel sheet with a table in it. For column Q, I want to add a formula only if column K's value is NOT 0, and column I's value is 0.
But instead of applying it to rows that met the condition, it is applying the formula to all rows under column Q.
I added if-statement, and it seems to be working when I run the program in debug mode, and check if the correct rows are going into the if condition.
What is weird is, if I try to put some random string into the rows for "else", it works! But I want nothing in those rows that don't satisfy the condition.
Dim lRow, i As Integer
lRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
For i = 2 To lRow 'Starts from i=2 because i=1 is the headers
If Range("K" & i).Value <> 0 And Range("I" & i).Value = 0 Then
Range("Q" & i).FormulaR1C1 = "=RC[-6]" 'This is the formula.
Else
Range("Q" & i).Value = "" 'Doesn't work.
Range("Q" & i).Value = "XXX" 'Works, but it inserts "XXX" to the cells. Ideally, I dont want anything, any formula in the cells.
End If
Next i
I expect that the rows that satisfy the condition should get the formula inserted under column Q, but I don't see why my code doesn't work.
As GSerg points out in the comments this behaviour is due to Excel autofilling the formula as it is in a table.
You can insert the following into your code which will turn off the autofill:
Application.AutoCorrect.AutoFillFormulasInLists = False
Remember to set it back to True again if it is desired behaviour for you normally (or if you are sharing this macro with others).

Inserting a formula all the way to the last row in the last empty column

I am fairly new to writing macros in VBA, but I am doing my best to learn as much as I can as quickly as possible. Anyway, the task I am trying to perform is pretty simple, but I'm having trouble coming up with a way to do it.
What I want to do is paste a formula into all of the rows in the last empty column of a spreadsheet.
So in this case, into the highlighted cells shown in the screenshot:
Example:
However, I don't want to rely on typing ("K1:K" & lastrow), what I want to do is create reference to the last column and the last row.
So far I've only been able to paste the formula into the entire column by using this:
lastcol = .Cells(1, .Columns.Count).End(xlToLeft).Offset(0, 1).Column
fvlookup = "=vlookup(#1,#2,#3,False)"
fvlookup = Replace (fvlookup, "#1", rng.Address)
fvlookup = Replace (fvlookup, "#2", [LookupFile.csv]LookupFile!$B:$1")
fvlookup = Replace (fvlookup, "#3", "5")
.Columns(lastcol).Formula = fvlookup
But later on in the process I'm working on, I want to remove all of "#N/A" and place them into a different tab named "JEs" because some of the items in the table actually don't have a value in the table I'm looking up to, and need JEs created for them. So, I would have a lot of unnecessary rows in the new tab if I went down this route.
Anyway, I've tried this:
lastcol = .Cells(1, .Columns.Count).End(xlToLeft).Offset(0,1).Column
fvlookup = "=VLOOKUP(#1,#2,#3,False)"
fvlookup = Replace(fvlookup, "#1", rng.Address)
fvlookup = Replace(fvlookup, "#2", "[LookupFile.csv]LookupFile!$B:$I")
fvlookup = Replace(fvlookup, "#3", "5")
With .Columns(lastcol)
lrow = .range("A" & .Rows.Count).End(xlUp).Row
.Rows(lrow).Formula = fvlookup
End With
But it only places the formula into "K1" (referencing the attached image)
I've also tried selecting this value after the formula is pasted and auto filling (I know it is advised to avoid selecting ranges with vba, but I still wanted to try as a last resort), but it says it isn't allowed.
I've also tried using:
.range(lastcol & .range("A" & .Rows.Count).End(xlUp).Rows).Formula = fvlookup
But that gives me run-time error '1004': Application-defined or object-defined error. I tried creating a variable named 'lrange' and setting it similar to how I set lastcol, but no luck (it returns the same error message as above). I've also tried editing lastcol to lastcol.Column or .Columns(lastcol) in the above string, but still nothing.
I've tried researching similar questions and all of the recommendations advise defining two variables (a lastrow one and a lastcolumn one) and inserting the formula into that range, but that doesn't seem to work with what I'm using.
I feel like the process VBA is trying to execute is restricted to only being able to insert data into the entire column, or part of it, with the way I set the macro up, like it's not able to find the last column and insert all the way to the last row with the way I set it up. So I apologize if this is the case, or if I should have written it differently.
Any advise or direction anyone can provide on this topic would be much appreciated.
Thank you for your time!
Instead of looping at the end I would just use .FillDown
Cells(2, lastcol).FormulaR1C1 = fvlookup
Range(Cells(2, lastcol), Cells(lrow, lastcol)).FillDown
How about replacing your code with something like this:
Sub foo()
lastcol = .Cells(1, .Columns.Count).End(xlToLeft).Offset(0, 1).Column
fvlookup = "=VLOOKUP(#1,#2,#3,False)"
fvlookup = Replace(fvlookup, "#1", Rng.Address)
fvlookup = Replace(fvlookup, "#2", "[LookupFile.csv]LookupFile!$B:$I")
fvlookup = Replace(fvlookup, "#3", "5")
lrow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To lrow
.Cells(i, lastcol).Formula = fvlookup
Next i
End Sub
This will loop from row 2 to lastrow and add the formula to lastcol.
As long as the table doesn't have an entirely blank row or column (as it shouldn't) Range("A1").CurrentRegion identifies the extent of the table. Then .Rows.Count and .Columns.Count gives you the information you need to be able to populate the adjacent column with a formula.
You can also fill the column's cells with formulas in one go, using FormulaR1C1 - provided you are careful with cell referencing. Here is an example:
Dim tableRange As Range
Dim x As Integer, y As Integer
Set tableRange = Range("A1").CurrentRegion
x = tableRange.Rows.Count
y = tableRange.Columns.Count
'fill the adjacent column with a SUM function summing across each row
Range(Cells(2, y + 1), Cells(x, y + 1)).FormulaR1C1 = "=SUM(RC[-" & y & "]:RC[-1])"
(You can also use y and 1 to give this new column a heading.)
If you need to replicate VLOOKUP with a specific (absolute) address such as $B:$I then I would first name that range and insert the name in the formula.
An example of such is:
.FormulaR1C1 = "=VLOOKUP(RC[-1],mylookup,2,FALSE)"
where mylookup is the range name and RC[-1] is referencing the cell immediately to the left of each formula.

Fill in the blanks excel formula to replace particular text in a cell

I'm looking for a formula to find and replace particular piece of text in a cell.
It sound a bit confusing but you can see what I mean by viewing the following image.
What I'm trying to achieve is when I fill for example cell B1 I would like to replace "SYS-NAME" in cell A25 and other cells where "SYS-NSME" is present.
You need to replace the ** before and after your values. You could change it to "" instead if you want to highlight those inserted values. ** will cause the entire cell to be replaced, instead of its match.
So the code splits column A into 2 sub columns. The first column runs until the first blank row, this contains all your variables and their new value. The second column runs until the end of the last used row. This contains your configuration with the variables that need to be changed.
Sub FindReplace()
Dim NewText, OldText As String
Dim LastRowText, i As Integer
LastRowText = Range("A1").End(xlDown).Offset(1, 0).Row
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
i = 1
Do While i < LastRowText
OldText = Range("A" & i).Value
NewText = Range("B" & i).Value
With ActiveSheet.Range("A" & LastRowText & ":A" & LastRow)
.Replace OldText, NewText, xlPart
End With
i = i + 1
Loop
End Sub
Option without a macro
In your configuration, edit each line with a variable to the following format. This will instantly update the configuration file too.
Cell A25: ="sysname " & B1
Cell A34: ="irf domain " & B2
...
The short answer would be
=SUBSTITUTE(A1,"**SYS-NAME**","MYSYSNAME")
starting in B1.

Colour an entire row based on the contents of one of its cells

I'm trying to color a spreadsheet based on the results given in one of it's columns. I'm using the following code:
With newSheet.Range("B:B")
.FormatConditions.Add(Excel.XlFormatConditionType.xlCellValue, Excel.XlFormatConditionOperator.xlEqual, "CORRECT")
.FormatConditions(1).Interior.ColorIndex = 4
.FormatConditions.Add(Excel.XlFormatConditionType.xlCellValue, Excel.XlFormatConditionOperator.xlEqual, "INCORRECT")
.FormatConditions(2).Interior.ColorIndex = 3
End With
Unfortunately this only colors the cell containing "CORRECT" or "INCORRECT". I'd like it to extend to the row they are in (for example, if B12 contains "CORRECT", I want A12:G12 to all be coloured green). It was suggested that I try using an expression and so I tried the following code:
.FormatConditions.Add(Type:=XlFormatConditionType.xlExpression, Formula1:="=B" & row & "= ""CORRECT"")")
.FormatConditions(1).Interior.ColorIndex = 4
This however, returns an E_INVALIDARG exception. I'd appreciate any tips on how to go about fixing this. I should also note that looping through every row and checking one at a time is not really an option, as there are many thousands of lines.
Your formula should work once you remove your excess closing parenthesis and make the column an absolute value
.FormatConditions.Add(Type:=XlFormatConditionType.xlExpression, Formula1:="=$B1= ""CORRECT""")
.FormatConditions(1).Interior.ColorIndex = 4
Make sure you set the row in your formula $B1 as the first row of your formatted range (you don't need to do a loop)
You can paste this into the sheet(s) in question:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Integer
i = 1
While Range("B" & i).Value2 <> ""
If Range("B" & i).Value2 = "INCORRECT" Then
Range("A" & i & ":G" & i).Interior.ColorIndex = 3
ElseIf Range("B" & i).Value2 = "CORRECT" Then
Range("A" & i & ":G" & i).Interior.ColorIndex = 4
Else
Range("A" & i & ":G" & i).Interior.ColorIndex = 0
End If
i = i + 1
Wend
End Sub
This assumes your data starts in row 1 (otherwise change the starting value of i).
This is a very, very low-tech answer. But after you've got the cells highlighted in the color you need them to be (using the code), copy all the values in the column and do a paste-special for "Formats" on the rows themselves.
Problem with that is that it'll be static, and if your values change with inputs, the coloring on the rows will be off.
But if it's a one-time thing, that may work.
If you do this, make sure that the column you're evaluating has a cell format type (ie: "General", "Text", etc) that's compatible with the data in the rows you're pasting onto.
Kludgey, but if you absolutely need this fast and you only need to do it once, it might work.
Edit: Pretty sure Kevin's answer below is a better one, as it actually solves it with code and seems like it'd work even if the values change in the evaluated cells.

Resources