VBA - multiple conditions for each cell - excel

I'm trying to solve this code's issue, which I can't run:
'========================================================================
' CHECKS IF MARKET SECTOR IS EMPTY (FOR LEDGER)
'========================================================================
Private Sub Fill_MarketSector()
Dim LastRow As Long
Dim rng As Range, C As Range
With Worksheets("Ready to upload") ' <-- here should be the Sheet's name
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' last row in column A
Set rng = .Range("A2:A" & LastRow) ' set the dynamic range to be searched
Set rng2 = .Range("F2:F" & LastRow)
' loop through all cells in column A and column F
For Each C In rng and For Each C in rng2
If rng.C.Value = "Ledger" and rng2.C.value IsEmpty Then
C.Value = "599" ' use offset to put the formula on column "L"
End If
Next C
End With
End Sub
The code should check if the column A contains word "Ledger" and column F is empty, then it should put into column F "599". It should always check to the very last row. Could you help me, please?
Thanks a lot!

You can access the accompanying cells in column F by looping through the cells in column A and using .Offset for column F then offset again to put the value in column L.
' loop through all cells in column A and column F
For Each C In rng
If LCase(C.Value) = "ledger" and IsEmpty(C.Offset(0, 5) Then
C.Offset(0, 11) = 599 'use offset to put the number on column "L"
End If
Next C

Related

Copy columns based on the autofiltered column, then paste value only to that autofiltered column

I want to filter column B based on values like "Unknown", then filter L column to have un-null values. copy the L column.
Paste values only to the column B.
Before:
ColumnB ..... Column L
1 ..... a
2 ..... b
Unknown.c
3.......d
Unknown.e
Unknown.
After
1 ..... a
2 ..... b
c.......c
3.......d
e.......e
Unknown..
Set r1 = Range("B:B").SpecialCells(xlCellTypeVisible)
Set r2 = Range("L:L").SpecialCells(xlCellTypeVisible)
Set myMultipleRange = Union(r1, r2)
Application.ScreenUpdating = False
sh1.Range("B:L").AutoFilter
sh1.Range("B:B").AutoFilter Field:=1, Criteria1:="Unknown", Operator:=xlFilterValues
sh1.Range("L:L").AutoFilter Field:=11, Operator:=xlFilterValues, Criteria1:="<>"
LstRw = sh1.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 1
If LstRw <> 0 Then
myMultipleRange.FillLeft
End If
The above code will copy and paste including the format.
Copy/paste in a filtered table is no good idea, because it inserts data continously even in hidden rows and messes up your data.
I recommend the following:
Filter data
Loop through all visible cells and copy the data row by row
If the following data is given …
… and you want to replace unkown with the data in column L, you can do the following:
Option Explicit
Public Sub FilterAndCopy()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Tabelle1")
'Filter data
ws.Range("B:B").AutoFilter Field:=1, Criteria1:="Unknown", Operator:=xlFilterValues
Dim LastRow As Long
LastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
Dim DestinationRange As Range
On Error Resume Next 'next line throws error if filter returns no data rows
Set DestinationRange = ws.Range("B2", "B" & LastRow).SpecialCells(xlCellTypeVisible) 'find visible cells between B2 (exclude header) and last row in B
On Error GoTo 0 'always re-activate error reporting!
If Not DestinationRange Is Nothing Then 'do it only if there is visible data
Dim Cell As Range
For Each Cell In DestinationRange 'copy each value row wise
Cell.Value = Cell.Offset(ColumnOffset:=10).Value 'column L is 10 columns right of B
Next Cell
End If
End Sub
Alternative solution - simply go through each cell in column B and replace "Unknown" with a respective value in column L.
Sub foo()
Dim lngLastRow As Long
Dim rngCell As Range
With Sheet1
LastRow = .Range("B" & Rows.Count).End(xlUp).Row
For Each rngCell In .Range("B1:B" & LastRow)
If rngCell.Value = "Unknown" Then
rngCell.Value = .Range("L" & rngCell.Row).Value
End If
Next rngCell
End With
End Sub
P.S. Make sure to replace With Sheet1 statement with a relevant sheet name/code.

Calculation of values based on the color of cells in Excel VBA

The code shows a simple average calculation based on the values in the defined cells. Those cells are highlighted in three colors. The aim is to take the values into the calcuation which cell color is e.g. green. I know the "if" command is needed, I just dont know where excatly to put it in:
Dim wb As Workbook, wq As Object
Dim ws As Worksheet, datdatum
Dim cell As Range, cell2 As Range, col As Long
ws.Range("H104:U104").Formula = "= Average(H34,H39,H68,H71,H83)"
I'll assume that entire rows are not green and that each column needs to be looked at independently.
Loop through each column from H to U. Loop through each cell in each column. Build a union of the cells that are green and average the union. Move on to the next column.
There is no point in building a formula for each column since any change would require rerunning the sub procedure. These will work on both manually set and conditional formatted cell colors.
.DisplayFormat does not work within a User Defined Function.
dim c as long, r as long, rng as range
with worksheets("sheet1")
for c =8 to 21
for r=2 to 103
if .cells(r, c).displayformat.interior.color = vbgreen then
if rng is nothing then
set rng = .cells(r, c)
else
set rng = union(rng, .cells(r, c))
end if
end if
next r
if not rng is nothing then _
.cells(104, c) = application.average(rng)
'alternate
'if not rng is nothing then _
'.cells(104, c).formula = "=average(" & rng.address(0,0) & ")"
next c
end with
Alternate,
dim c as long
with worksheets("sheet1")
if .autofiltermode then .autofiltermode = false
for c =8 to 21
with .range(.cells(1, c), .cells(103, c))
.AutoFilter Field:=1, Criteria1:=vbgreen, Operator:=xlFilterCellColor
.cells(104, c) = application.subtotal(101, .cells)
.AutoFilter
end with
next c
end with

Deleting cells and corresponding row if criteria is met

I have a spreadsheet that has columns from A5 to AA5 and has data from A6 to AA10000. In cells A1, a user inputs a value, in cell A2 is a drop box that contains the headers of columns X to AA (A, B, C, D), and in A3 I have a dropdown of logical operators (<,>,<>,=). I'm trying to write a script that goes through columns X to AA and remove the cells that met a criteria that a user sets, e.g. user inputs a value of 300, a header "B" and a logical operator "<" and the macro goes through column Y which has the header "B" and deletes all values that are less than 300, the deletes the row from A to AA.
So far I've attempted this:
Sub removedata()
Dim ws As Worksheet
Dim rng As Range
Dim headerval As Variant
Dim sign As Variant
Dim inputval As Variant
Dim b_header As Range
Dim Cell As Range
Set ws = Worksheets("Sheet1")
Set rng = ws.Range("X5:AA5000")
Set b_header = ws.Range("X5:X5000")
inputval = cells(1, 1).Value
headerval = cells(2, 1).Value
sign = cells(3, 1).Value
For Each Cell In b_header.cells
If (headerval = "B") And (sign = "<") And (inputval < Cell.Value) Then
Cell.Delete
End If
Next Cell
End Sub
I've only attempted it for B column as a test to see whether or not I could get something to happen. When I run this Macro, it just buffers for a second and then nothing else happens.
Any help would be greatly appreciated!
Edit: Actually I realised it deletes the values that are greater than the input (Cell A1), however it only deletes a few of them each time I run it, it also moves the cells below it to its position.
The COUNTIF/COUNTIFS worksheet function accepts and interprets criteria as strings. You can use with Evaluate or directly through an application object.
Option Explicit
Sub delSpecial()
Dim lr As Long, i As Long, c As String, cl As Long
With Worksheets("sheet6")
c = .Cells(3, "A").Value & .Cells(1, "A").Value
cl = Application.Match(.Cells(2, "A").Value, .Rows(5), 0)
lr = Application.Max(.Cells(.Rows.Count, "X").End(xlUp).Row, _
.Cells(.Rows.Count, "Y").End(xlUp).Row, _
.Cells(.Rows.Count, "Z").End(xlUp).Row, _
.Cells(.Rows.Count, "AA").End(xlUp).Row)
For i = lr To 6 Step -1
If CBool(Application.CountIf(.Cells(i, cl), c)) Then
.Cells(i, "A").Resize(1, 27).Interior.Color = vbYellow
'.Rows(i).EntireRow.Delete
End If
Next i
End With
End Sub

macro to copy formula down if adjacent cell not blank

Okay folks, I have this simple table below and I am trying to calculate a macro vba formula in column G as long as column c has a value. All the info in the spreadsheet is already pulled in from a previous macro. Here is what I have....
Sub Macro1()
'
' Macro1 Macro
'
Dim x As Long
x = CLng((d2 + e2) / c2)
For Each r In Intersect(ActiveSheet.UsedRange, Range("C:C"))
If r.Value <> "" Then
r.Offset(1, 5).Value = x
End If
Next r
End Sub
Try the code below, it will loop through Column C (until last row with value in it), and will calculate your formula with the relevant parameters of that row in Column G.
Note: your formula of (D+E)/C will give you small values, as C has high values. If that's the formula you want to use, than you need to change the output from Long to Double to show the numbers after the 0..
Code
Option Explicit
Sub Macro1()
' Macro1
Dim r As Range
Dim LastRow As Long
' modify "Sheet1" to your sheet's name
With Sheets("Sheet1")
' find last row with data in Column C ("Salary")
LastRow = .Cells(.rows.Count, "C").End(xlUp).Row
For Each r In .Range("C2:C" & LastRow)
If r.Value <> "" Then
r.Offset(0, 4).Value = CDbl((Range("D" & r.Row).Value + Range("E" & r.Row).Value) / r.Value)
End If
Next r
End With
End Sub
Try this:
Range("G2:G" & Range("C" & Rows.Count).End(xlUp).Row).Formula = "=CONCATENATE(C2,"", "",B2)"
Counts rows in column C, if not empty, fills in Concatenation formula that you can change to your formula.
You refer to cells as Range("D2") etc rather than just d2.

Write cell value from one column to a location specified by other cells

I have a value in Column A which I want to write to a separate sheet, there are column and row numbers which specify the location I want to write that value in the same row as the value in column A.
For instance the value in A8 has column number "2" in Q8 and row number "118" in S8. So I want to write a formula in the new sheet which puts the value of A8 into cell B118 in the new sheet. And for this to go down with all the values in A:A as the first sheet continues to be filled in.
I've tried doing this with sumifs formula here but its not quite working out;
=IF(SUMIFS(sheet1!$A:$A,sheet1!$Q:$Q,COLUMN(B8),sheet1!$S:$S,ROW(B8))," ",sheet1!$A:$A)
If you want the formula in the new sheet to reference the cell in Sheet1 then:
Sub marine()
Dim cl As Long, rw As Long, source As String
cl = Range("Q8").Value
rw = Range("S8").Value
Sheets("new").Cells(rw, cl).Formula = "=Sheet1!A8"
End Sub
and if you simply want A8's value transferred to the new sheet, then:
Sub marine2()
Dim cl As Long, rw As Long, source As String
cl = Range("Q8").Value
rw = Range("S8").Value
Sheets("new").Cells(rw, cl).Value = Range("A8").Value
End Sub
EDIT#1:
Here is a version that will handle the entire column:
Sub marine3()
Dim cl As Long, rw As Long, source As String
Dim i As Long, N As Long
N = Cells(Rows.Count, "A").End(xlUp).Row
For i = 8 To N
cl = Range("Q" & i).Value
rw = Range("S" & i).Value
If cl <> 0 And rw <> 0 Then
Sheets("new").Cells(rw, cl).Value = Range("A" & i).Value
End If
Next i
End Sub
Here is my answer.
Sub movindData()
'take all the data from sheet1 and move it to sheet2
Dim sht2 As Worksheet
Dim r
Dim c
Dim i
Dim rng As Range
Dim A 'for each value in column A
Dim Q 'for each value in column Q (the column)
Dim S 'for each value in column S (the row)
r = Range("A1").End(xlDown).Row 'the botton of columns A, the last row
'I take the inicial cells as a A1, but you
'can change it as you need.
c = 1 'the column A
Set rng = Range(Cells(1, 1), Cells(r, c)) 'this takes just the range with the data in columns A
Set sht2 = Sheets("Sheet2")
For Each i In rng
A = i.Value 'Store the value of every cell in column A
Q = i.Offset(0, 16).Value 'Store the value of every cell in column Q (the destination column in sheet2)
S = i.Offset(0, 18).Value 'Store the value of every cell in column s (the destination row in sheet2)
sht2.Cells(Q, S).Value = A
Next i
End Sub

Resources