IF statement with dynamic range VBA ─ Excel - excel

Good afternoon friends, I need your support because when I execute my macro in VBA, the results show the formula.
What I want is to be able to carry out an IF STATEMENT where only the conditions that I have put in the formula give me as a result, that is, only the text "Approved" or "Denied".
Here is my code that I currently have:
Sub if_status()
Range("D2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]=""Approved"",""Approved"",""Denied"")"
Selection.AutoFill Destination:=Range("D2:D" & Range("B" & Rows.Count).End(xlUp).Row)
Range(ActiveCell, ActiveCell.End(xlDown)).Select
End Sub
I have tried this new code but it won't let me put the "ELSE" and it finally gives me an error. And neither if how to do the autocomplete until the last row:
Sub ANOTHER()
Range("D2").Select
If Range("C2").Value = "" Then Range("e2").Value = "Denied"
Else
Range("D2").Value = "Approved"
End If
End Sub

Dim ws As Worksheet
Set ws = ActiveSheet 'always specify a worksheet
With ws.Range("D2:D" & ws.Cells(Rows.Count, "B").End(xlUp).Row)
.Formula = "=IF(C2="""",""Denied"",""Approved"")" 'apply formula
.Value = .Value 'convert to value
End With

If you put something after Then on the same line, you cannot continue it on a new line.
The Then part needs its own line.
Sub ANOTHER()
Range("D2").Select
If Range("C2").Value = "" Then
Range("e2").Value = "Denied"
Else
Range("D2").Value = "Approved"
End If
End Sub
If I understand correctly, your other question can be done with this one line.
Range("C1:C" & Range("B" & Rows.Count).End(xlUp).Row).Formula2R1C1 = "=IF(RC[-1]=""Approved"",""Approved"",""Denied"")"
This assumes you have your B and C columns defined correctly.
With your code you are determining the last row using Column B, and then setting Column C based on Column B. Is that correct?

I found the way the formula is not displayed in the results and the USER can only see values. Additionally, the code validates until the last one that contains a value.
The code validates until the last row of column [B] and the IF statement validates the data of column [C] and leaves the result in column [D] only values do not show the formula..
Sub another_code()
Dim cell As Range
Set rng = Range("C2:C" & Range("B" & Rows.Count).End(xlUp).Row)
For Each cell In rng
If cell.Value <> "" Then
cell.Offset(0, 1).Value = "Approved"
Else
cell.Offset(0, 1).Value = "Denied"
End If
Next cell
End Sub

Related

bold cell based on specific value in column J

I already tried using this code and its not working
Sub Bold()
With Sheets("1470")
For Each Cell In Range("J:J")
If Cell.Value = "N/A" Then
Cell.Font.bold = True
End If
Next Cell
End With
End Sub
the output that I want to execute is every cell in column J that contains "N/A" gets bold
I got error
"Type mismatch"
Do not use J:J It will slow your code. Find the last row and then check in that range.
To specifically check for #N/A use CVErr() as shown below.
If you want to check for any error then go with IsError() as mentoned by #PawelCzyz.
Is this what you are trying?
With Sheets("1470")
lrow = .Range("J" & .Rows.Count).End(xlUp).Row
For Each cell In Range("J1:J" & lrow)
If CVErr(cell.Value) = CVErr(xlErrNA) Then
cell.Font.Bold = True
End If
Next cell
End With
This answer is based on the assumption you looking for #N/A errors on your worksheet caused by the same formulas in that column.
Sub Test()
Dim rng1 As Range, rng2 As Range
With ThisWorkbook.Sheets("1470")
Set rng1 = .Range("J1:J" & .Range("J" & .Rows.Count).End(xlUp).Row)
If .Evaluate("=SUM(--ISNA(" & rng1.Address & "))") > 0 Then
Set rng2 = Intersect(rng1, rng1.SpecialCells(xlCellTypeFormulas, xlErrors))
rng2.Font.Bold = True
End If
End With
End Sub

Search for partial text within a row of data in a cell and extract whole string and row underneath

I'm trying to clean up some data in a column in Excel but it has too many rows to do it manually and the data I want is mixed up with irrelevant values.
Essentially, I need a VBA macro to search each cell in column A of Sheet1 for any row that contains the partial string "SAAM" and then copy both the full string attached to it and the next row of data directly underneath each instance to a separate sheet (Sheet2).
I expect the output to show what is shown in the attached image. I put the expected result in column B for clarity but I really want it in Sheet2 Column A.
My script currently ends up moving the full contents of the cell to Sheet2.
Sub Test()
For Each Cell In Sheets(1).Range("A:A")
If InStr(Cell.Value, "SAAM") > 0 Then
matchRow = Cell.Row
Rows(matchRow & ":" & matchRow + 1).Select
Selection.Copy
lastRow = ActiveSheet.UsedRange.Rows.Count
If lastRow > 1 Then lastRow = lastRow + 1
ActiveSheet.Range("B" & lastRow).Select
ActiveSheet.Paste
Sheets("Sheet1").Select
End If
Next
End Sub
Something like this (note this was based on looking at your code, not at the screenshot, which tells a different story...)
Sub Test()
For Each Cell In Sheets(1).UsedRange.Columns(1).Cells
If Not IsError(Cell.Value) Then
If InStr(Cell.Value, "SAAM") > 0 Then
'copy to first empty row
Cell.Resize(2,1).Entirerow.copy _
Sheets(2).Cells(rows.count, 1).end(xlup).offset(1,0)
End If 'has substring
End If 'not error
Next
End Sub
Edit: seem like you want something more like this, based on your screenshot (untested)
Sub Test()
Dim arr, i as long, sep
For Each Cell In Sheets(1).UsedRange.Columns(1).Cells
If Not IsError(Cell.Value) Then
If InStr(Cell.Value, "SAAM") > 0 Then
arr = Split(Cell.Value, vbLf) 'split cell content on newline
sep = ""
For i = lbound(arr) to ubound(arr)-1
if arr(i) like "*SAAM*" then
with cell.offset(0, 1)
.value = .value & sep & arr(i) & vbLf & arr(i+1)
sep = vbLf & vbLf
end with
end if
Next i
End If 'has substring
End If 'not error
Next
End Sub
Based on your code I’ll modify it this way:
Sub Test()
For Each Cell In Sheets(1).Range("A:A")
If InStr(Cell.Value, "SAAM") > 0 Then
matchRow = Cell.Row
Sheets(1).Cells(matchRow,1).Copy
lastRow = Sheets(2).Cells(Rows.Count,1).End(xlUp).Row + 1
Sheets(2).Range("B" & lastRow).Select
Sheets(2).PasteSpecial Paste:=xlPasteValues
Sheets(1).Select
End If
Next
End Sub

Copy and paste if one cell is blank and the other is not

So data gets pasted in to column B as the code keeps running it'll do a condition check to see there's any values in column B and paste a value in to the adjacent column A. I need to make it so it does two condition checks:
If there's values in column b, but then to check if there's values in column A before pasting so it doesn't overwrite different data that's been pasted already.
For Each Cell In y.Sheets("Compiled").Range("A:B")
If Range("B:B").Value <> "" And Range("A:A").Value = "" Then
Cell.Offset(0, -1).PasteSpecial xlPasteValues
End If
Next
You were close, don't try to loop over a multiple column range:
Sub Test()
For Each Cell In y.Sheets("Compiled").Range("B:B")
If Cell.Value <> "" And Cell.Offset(0, -1).Value = "" Then
Cell.Offset(0, -1).Value = Cell.Value
End If
Next
End Sub
NOTE: You are looping through every cell in Range("B:B") which is probably unnecessary. It'd be better if you use a lastrow value, or a static range like Range("B2:B1000"). Or you could use a criteria to exit your loop like If Cell.Value = "" Then Exit For.
Here's a version of the code that implements the lastrow value that dwirony mentioned in their answer. This also throws everything in arrays, so it might go a bit faster if you have a really large dataset.
Option Explicit
Sub test()
Dim ACol As Variant
Dim BCol As Variant
Dim lastrow As Long
Dim i As Long
lastrow = Range("B:B").Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).row
BCol = Range("B1:B" & lastrow).Value
ACol = Range("A1:A" & lastrow).Value
For i = LBound(BCol) To UBound(BCol)
If IsEmpty(ACol(i, 1)) And Not IsEmpty(BCol(i, 1)) Then
ACol(i, 1) = BCol(i, 1)
End If
Next i
Range("A1:A" & lastrow).Value = ACol
End Sub

Excel - How to fill in empty lines below with current value until new value is met in the same column. Non-VBA solution needed [duplicate]

I want to fill in all empty cells using values of above cells
state name
IL Mike
Sam
CA Kate
Bill
Leah
Should be as follows
state name
IL Mike
IL Sam
CA Kate
CA Bill
CA Leah
I tried the following
Sub split()
Dim columnValues As Range, i As Long
Set columnValues = Selection.Area
Set i = 1
For i = 1 To columnValues.Rows.Count
If (columnValues(i) = "") Then
columnValues(i) = columnValues(i - 1)
End If
Next
End Sub
I get an error when I set i. How can I modify my code
For those not requiring VBA for this, select ColumnA, Go To Special..., Blanks and:
Equals (=), Up (▲), Ctrl+Enter
should give the same result.
Given you asked for VBA, there is a quicker way than looping (the VBA equivalent of what pnuts posed above, with the additional step of removing the formula at the end):
On Error Resume Next
With Selection.SpecialCells(xlCellTypeBlanks)
.FormulaR1C1 = "=R[-1]C"
.Value = .Value
End With
It is because i should be defined as i=1. There are although a few other problems with the code. I would change it to something like this:
Sub split()
Dim columnValues As Range, i As Long
Set columnValues = Selection
For i = 1 To columnValues.Rows.Count
If columnValues.Cells(i, 1).Value = "" Then
columnValues.Cells(i, 1).Value = columnValues.Cells(i - 1, 1).Value
End If
Next
End Sub
Sub fill_blanks()
Dim i As Long
i = 2 ' i<>1 because your first raw has headings "state " "name"
'Assume state is in your cell A and name is in your cell B
Do Until Range("B" & i) = ""
Range("B" & i).Select
If ActiveCell.FormulaR1C1 <> "" Then
Range("A" & i).Select
If ActiveCell.FormulaR1C1 = "" Then
Range("A" & i - 1).Copy
Range("A" & i).PasteSpecial Paste:=xlPasteValues
Else
i = i + 1
End If
Else
i = i + 1
End If
Loop
End Sub
For some cause the method used on post https://stackoverflow.com/a/20439428/2684623 not work for me. When the line .value=.value is executed, I get the error 'not available' (#N/D for local language) in the value of cells. Version of Office is 365.
I dont know the reason however with some modifications runs fine:
Sub TLD_FillinBlanks()
On Error Resume Next
With ActiveSheet.UsedRange.Columns(1)
If .Rows(1) = "" Then .Rows(1).Value = "'"
.SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C"
.Value = .Value
End With
End Sub
Using loops:
Sub TLD_FillinBlanksLoop()
Dim rCell As Range
For Each rCell In ActiveSheet.UsedRange.Columns(1).Cells
If rCell.Value = "" And rCell.Row > 1 Then
rCell.FillDown
End If
Next
End Sub
I hope that can be useful for somebody. Thanks and regards.
Here is the whole module, I pasted the formulas as values at the end.
Sub FillBlanksValueAbove()
Dim sName As String
sName = ActiveSheet.Name
Dim ws As Worksheet
Dim lastRow As Long, lastCol As Long
Dim rng As Range
'Set variable ws Active Sheet name
Set ws = Sheets(sName)
With ws
'Get the last row and last column
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
'Set the range
Set rng = .Range(.Cells(1, 1), .Cells(lastRow, lastCol))
rng.Select
'Select Blanks
rng.SpecialCells(xlCellTypeBlanks).Select
'Fill Blanks with value above
Selection.FormulaR1C1 = "=R[-1]C"
'Paste Formulas as Values
rng.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
End With
End Sub

Assistance with comparing cells with If formula

I am Comparing cells in column D and if they match paste the value of the previous cell in column B into the next cell in column B if they do not match paste the value of the subseqent cell in column A into the cell in column B
e.g
IF(D2=D3,B2,A2+1)" but this is not working after running on the 1st sequence of cells in D I get #Valve!" for the rest of column B
I am sure this is the problem IF(D2=D3,B2,A2+1)" in-particular the A2+1 reference but not sure how to call it
(Sorry if this was unclear)
Thanks
Sub TargetId()
Dim lRow As Long
Dim ws As Worksheet
Set ws = Sheets("UnPivot")
Columns("B:B").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("B1").FormulaR1C1 = "Source"
Range("B2").FormulaR1C1 = [A2].Value
With ws
lRow = ws.Range("D" & .Rows.Count).End(xlUp).Row
With .Range("B3:B" & lRow)
.Formula = "=IF(D2=D3,B2,A2+1)"
.Value = .Value
End With
End With
End Sub
As follow up from comments, this one works:
With .Range("B3:B" & lRow)
.Formula = "=IF(D2=D3,B2,A3)"
.Value = .Value
End With

Resources