VBA Check if Value is in the list with condition - excel

Sub PullUniques()
LastRowColumnA = Cells(Rows.Count, 1).End(xlUp).Row
Dim rngCell As Range
For Each rngCell In Range("A1:A" & LastRowColumnA)
If WorksheetFunction.CountIf(Range("B1:B" & LastRowColumnA), rngCell) <> 0 And _
Range(WorksheetFunction.CountIf(Range("B1:B" & LastRowColumnA), rngCell) <> 0).Offset(0, 1).Row <= 0 Then
MsgBox "Please correct Item" & rngCell & " Amount Data"
End If
Next
This code is looking up Column B to see if column A has any same values.
The code works fine if I do not use second line of if statement, but when I tried to add second condition column A is matching B and column C's value is not greater than 0, it does not work. How can I make this code work?

I think you are trying to check,
1) if the value in A exist in column B and
2) if TRUE, is the value in column C less than or equal to 0.
If that's what you need, the code below should work.
Sub PullUniques()
LastRowColumnA = Cells(Rows.Count, 1).End(xlUp).Row
Dim rngCell As Range
For Each rngCell In Range("A1:A" & LastRowColumnA)
If WorksheetFunction.CountIf(Range("B1:B" & LastRowColumnA), rngCell) <> 0 And _
Range("C" & rngCell.Row).Value <= 0 Then
MsgBox "Please correct Item" & rngCell & " Amount Data"
End If
Next
End Sub
However, if your condition is,
1) if the value in A the same as value in B and
2) if TRUE, is the value in column C less than or equal to 0.
then you don't need to use countif
Sub PullUniques()
LastRowColumnA = Cells(Rows.Count, 1).End(xlUp).Row
Dim rngCell As Range
For Each rngCell In Range("A1:A" & LastRowColumnA)
Debug.Print Range("B" & rngCell.Row).Value & "/" & Range("C" & rngCell.Row).Value
If Range("B" & rngCell.Row).Value = rngCell And _
Range("C" & rngCell.Row).Value <= 0 Then
MsgBox "Please correct Item" & rngCell & " Amount Data"
End If
Next
End Sub

Related

VBA Excel InStr(myString) returns no result

I want to multiply my range of cells by -1 when they matches the Instr criteria.
but I still get positive values, which are based on my else statement.
Basically, I use the ConverdDecimal function from this link:
https://www.extendoffice.com/documents/excel/1497-excel-convert-decimal-degrees-to-degrees-minutes-seconds.html
with doesn't cope well with negative values. Hence I have to modify my code.
Sub Sun()
Dim rng As Range, cell As Range, rngB As Range, rngC As Range
Dim wors As Worksheet
Dim myString As String
Set wors = ThisWorkbook.ActiveSheet
Dim lastRow As Long, LastRow2 As Long
wors.Columns("E").Copy
wors.Columns("P").PasteSpecial xlPasteValues
wors.Columns("F").Copy
wors.Columns("R").PasteSpecial xlPasteValues
lastRow = wors.Range("P" & wors.Rows.Count).End(xlUp).Row
LastRow2 = wors.Range("Q" & wors.Rows.Count).End(xlUp).Row
Set rng = wors.Range("P1:P" & lastRow)
Set rngB = wors.Range("R1:R" & lastRow)
Set rngC = wors.Range("F1:F" & lastRow)
For Each cell In rng
cell = WorksheetFunction.Substitute(cell, " ", "° ", 1)
cell = WorksheetFunction.Substitute(cell, " ", "' ", 2)
Next
For Each cell In rngB
cell = WorksheetFunction.Substitute(cell, "-", "")
cell = WorksheetFunction.Substitute(cell, " ", "° ", 1)
cell = WorksheetFunction.Substitute(cell, " ", "' ", 2)
Next
With words
Range("Q2:Q" & lastRow).Formula = "=ConvertDecimal(P2)"
Columns("Q").Copy
Columns("X").PasteSpecial xlPasteValues
Range("S2:S" & lastRow).Formula = "=ConvertDecimal(R2)"
End With
With rngC
If InStr(myString, "-") <> 0 Then
Range("T2:T" & lastRow).Formula = "=S2 * -1 "
Else
Range("T2:T" & lastRow).Formula = "=S2"
End If
End With
End Sub
I tried:
Range("T2:T" & lastRow).Formula = "=S2 * (-1) "
Range("T2:T" & lastRow).Formula = "=-S2"
Range("T2:T" & lastRow).Formula = "=-1 * S2"
Nothing works
What is wrong with my code? Why does it cove only the Else situation? I need negative formulas wherever the "-" appears in column F.
Is there any reason why this would not work: For cell T2 use the formula
=IF(LEFT(TRIM(F2), 1)="-", -1, 1)*S2
or if you want to do it in VBA
Range("T2:T" & lastRow).FormulaR1C1="=IF(LEFT(TRIM(RC6), 1)=""-"", -1, 1)*RC[-1]"
is it failing because of this typo and you do not have option explicit?
With words
words is not defined but wors is so if no option explcit a variable words is created at runtime but is set to nothing so nothing happens inside the with block

Select range if - depending on a value of each cell of a range (VBA)

I want to select whole rows of a range (C14:M34) if value = 1 in a column(F14:F34). Otherwise I want to select the same rows except a specific column(G).
I can do this if I have only a single row but how can I apply this for a range (multiple rows)?
Hereby my code (which is not working):
ActiveSheet.Range("$C$13:$M$34").AutoFilter Field:=6, Criteria1:="<>"
Dim d As Range
For Each d In Range("F14:F34")
If d.Value = 1 Then
ActiveSheet.Range("C14:M34").Select
Else
Application.Union(Range("C14:F34"), Range("H14:M34")).Select
End If
Selection.Copy
Next d
Try this code, please:
Sub testSelecting()
Dim sh As Worksheet, rngSel As Range, i As Long
Set sh = ActiveSheet
For i = 14 To 34
If sh.Range("F" & i).Value = 1 Then
If rngSel Is Nothing Then
Set rngSel = sh.Range("C" & i & ":M" & i)
Else
Set rngSel = Union(rngSel, sh.Range("C" & i & ":M" & i))
End If
Else
If rngSel Is Nothing Then
Set rngSel = Union(sh.Range("C" & i & ":F" & i), sh.Range("H" & i & ":M" & i))
Else
Set rngSel = Union(rngSel, sh.Range("C" & i & ":F" & i), sh.Range("H" & i & ":M" & i))
End If
End If
Next i
If rngSel.Cells.count > 1 Then rngSel.Select: Stop
rngSel.Copy
End Sub
The code is not tested, because I do not have your file to do that. It is based only on logic. It stops after selection, in order to let you appreciate that the selected range is the one you need.
Please confirm that it works as you need, or what problem does it create, if any...

Create a checkpoint in a foreach statement

I am writing a code that put an X in a cell depending on a offset cell value, for exemple if the offset cell has a value of 3, it will put an X in the cell and decrement the offset cell value, i want to save the location of that cell and start the next for each with it.
For Each Cell In plage
If (Cell.Offset(0, 1).Value <> 0) Then
If (Cell.Value <> "X") Then
Cell.Offset(0, 1).Value = Cell.Offset(0, 1).Value - 1
Cell.Value = "X"
Checkpoint = Cell.Address
Exit For
Else
Cell.Value = ""
GoTo NextStep
End If
Exit For
Else
Cell.Value = ""
End If
NextStep:
Next Cell
The problem i am having with the current code is it start the loop all over again while i want it to keep till the end of the lines, until all offset value are equal to 0.
Try the below (there are notes on the code). If you face difficulties let me know.
Option Explicit
Sub test()
'In this example we assume that the data you want to loop appear in Column A
Dim i As Long, Lastrow As Long
Dim Checkpoint As Variant
With ThisWorkbook.Worksheets("Sheet1") '<- Change sheet name if needed
Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row '< -Fins the lastrow of the column you want to loop
For i = 2 To Lastrow ' < -Start looping from row 2 to Lastrow fo the column
If .Range("A" & i).Offset(0, 1).Value <> 0 Then '<- You are looping
If .Range("A" & i).Value <> "X" Then
.Range("A" & i).Offset(0, 1).Value = .Range("A" & i).Offset(0, 1).Value - 1
.Range("A" & i).Value = .Range("A" & i).Value & "X"
Checkpoint = .Range("A" & i).Address
Else
.Range("A" & i).Value = ""
End If
Else
.Range("A" & i).Value = ""
End If
Next i
End With
End Sub
Is plage a range?
If so, you could update it to start from the checkpoint and include all cells up to some lastCell for example.
Something like:
set plage=thisWorkbook.Worksheets("Your Worksheet").Range(checkpoint,lastCell)
That way the next For-Each should start from your checkpoint.
BTW if I understand correctly what you'e trying to do, I would suggest you replace cell.value="" with cell.clearContents

Using colum names in VBA

I have the below code which searches for specific text based on the Col header, like Col O, Col P etc. Instead I want to search using the respective column name in Row 1.
I have added the column name in the code comments.
Sub PassFailValidationandupdatecomments()
Dim Rng As Range, cl As Range
Dim LastRow As Long, MatchRow As Variant
With Sheets("DRG")
LastRow = .Cells(.Rows.count, "E").End(xlUp).Row '"E" - Live ASIN
Set Rng = .Range("E2:E" & LastRow) ' "E" - Live ASIN
End With
With Sheets("Latency")
For Each cl In .Range("B2:B" & .Cells(.Rows.count, "B").End(xlUp).Row) ` "B" - ASIN
MatchRow = Application.Match(cl.Value, Rng, 0)
If Not IsError(MatchRow) Then
Select Case Sheets("DRG").Range("AH" & MatchRow + 1).Value ' "AH" - Final Test Result
.Range("O" & cl.Row).Value = "Pass" '"O" - Pass/Fail
Case "Pended"
.Range("O" & cl.Row).Value = "Fail"'"O" - Pass/Fail
Case "In progress"
.Range("O" & cl.Row).Value = "In progress"'"O" - Pass/Fail End Select
If Not Sheets("DRG").Range("E" & MatchRow + 1).Value = vbNullString Then .Range("P" & cl.Row).Value = .Range("P" & cl.Row).Value & IIf(Not .Range("P" & cl.Row).Value = vbNullString, ";", "") & Sheets("DRG").Range("S" & MatchRow + 1).Value ' "E" - Live ASIN ; "P" - Comments ; "S" - App Trail
End If
Next cl
End With

Vlookup execution criteria

How can I modify the execution of the vlookup based upon a specific value. I want it to execute the Vlookup only if the output sheet (sheet 2) cell (Q2 to AB2) contains "Forecast" otherwise skip column if labeled "Actual" in the relative cell.
Finally I want to copy and paste any cells in the Column Q to AB that contain the vlookup forumla. I believe this can be accomplished using the String function.
Sub MakeFormulas()
Dim SourceLastRow As Long
Dim OutputLastRow As Long
Dim sourceSheet As Worksheet
Dim outputSheet As Worksheet
Dim X As Long
'names of our worksheets
Set sourceSheet = Worksheets("Sheet1")
Set outputSheet = Worksheets("Sheet2")
'Determine last row of source
With sourceSheet
SourceLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
With outputSheet
'Determine last row in col C
OutputLastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
For X = 2 To OutputLastRow
If InStr(1, .Range("C" & X), "PO Materials") + InStr(1, .Range("C" & X), "PO Labor") > 0 Then
'Apply formula
.Range("Q" & X & ":AB" & X).Formula = _
"=VLOOKUP($E" & X & ",'" & sourceSheet.Name & "'!$A$2:$L$" & SourceLastRow & ",Match(Q$1,'" & sourceSheet.Name & "'!$A$1:$AD$1,0),0)"
End If
Next
End With
End Sub
Sheet 2 Screenshot
I will just hardcode a bit:
For Y = 17 To 28 'Q to AB
For X = 2 To OutputLastRow
If InStr(1, .Range("C" & X), "PO Materials") + InStr(1, .Range("C" & X), "PO Labor") > 0 And Cells(2, Y) = "Forecast" Then
'Apply formula
.Cells(X, Y).Formula = _ 'cell at row X, column Y
"=VLOOKUP($E" & X & ",'" & sourceSheet.Name & "'!$A$2:$L$" & SourceLastRow & ",Match(" & cells(1,Y).address & ",'" & sourceSheet.Name & "'!$A$1:$AD$1,0),0)"
End If
Next
Next
It breaks down to check the second cell in each column first before applying the formula

Resources