Clear Excel Cell if Value less than another Cell value - vba

I am hoping someone can help, I need to clear cells when then value of is less that a value in another cell. I did use conditional formatting but this messes up calculations further into the sheet.
I used a guide and was able to remove cells when I inputted the fixed integer into the module but am unsure how I adapt this to refer to a cell instead of a fixed number.
Thank you.
Ed

I believe this is what you are looking for below, this will take a value from cell B1 and compare against values in Column A, and if the values are less than the value in B1, it will clear the contents of that cell:
Sub ClearLowerThan()
Dim c As Range, Rng As Range
Dim LastRow As Long
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare you worksheet, amend as required
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row with data on Column A
CompareVal = ws.Range("B1").Value
'get the value to compare against, in this case from cell B1
Set Rng = ws.Range("A1:A" & LastRow)
'set the range to compare against the value from B1
For Each c In Rng 'for each cell in the given range
If c.Value < CompareVal Then c.ClearContents
'if value of cell is less than the value to compare against, clear the cell contents.
Next
End Sub

Related

How to reference a range of cells in a row

This is a sample code. I am trying to get values of cells D9, E9 and F9
Private Sub test()
Dim myRange As Range
Dim lastrow As Long
Set ws1 = ThisWorkbook.Sheets("Sheet1")
lastrow = ws1.Range("A" & ws1.Rows.Count).End(xlUp).Row
Set myRange = ws1.Range("D9:F" & lastrow )
For Each cell In myRange
Debug.Print cell
Next cell
End Sub
But this cell also consist of values from column G and H. What am I missing?
Since you are trying to get the data for specific cells which you already know the addresses of (D9, E9, F9), you don't need to worry about getting the last row. Maybe you are trying to ask a different question? Maybe you want to get all of the data from row 9 to the last used used row for columns D, E, & F? Anyway, to answer the question asked, here is the modified code that will return the requested values:
Sub test()
Dim myRange As Range
Dim cell As Variant
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set myRange = ws1.Range("D9:F9")
For Each cell In myRange
Debug.Print cell
Next cell
End Sub

Compare rows (and cells within those rows) on two spreadsheets using VBA in Excel, highlight differences

I am trying to take two sheets in a workbook and highlight cells in Sheet2 that are different from Sheet1. The sheets can range from a small number of rows to hundreds of them. I will be happy to answer any questions, I have never used VBA before, but I have experience in other languages.
It needs to go by Sheet2's rows, then cells within the current row. Take the first cell in the row and see if the contents of that cell exists within Sheet1, if that cell's contents don't exist, highlight the whole row as a new entry. If the contents do appear in Sheet1, go through each cell of the row that entry appears on in each sheet and highlight changes on only Sheet2.
All I have figured out so far:
Sub DetectChanges()
Rem compares two sheets by row. let sheet1 be the old one and sheet2 be the new one.
Rem *hopefully* highlights any differences. Make column1 unique identifiers
Dim ws1, ws2 As Worksheet
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
For Each rw In ws2.Rows
' check identifier for active row & detect changes
Next
End Sub
Thank you for any help!
edited after OP's clarifications
this (commented) code should get you on the right way:
Option Explicit
Sub DetectChanges()
Dim ws1 As Worksheet, ws2 As Worksheet '<-- explicitly declare each variable type
Dim ws1Data As Range, f As Range, cell As Range
Dim icol As Long
Set ws1Data = Worksheets("Sheet01").Columns(1).SpecialCells(xlCellTypeConstants) '<-- set a range with Sheet1 cells containing data
With Worksheets("Sheet02") '<--| reference Sheet2
For Each cell In Intersect(.UsedRange, .Columns(1)).SpecialCells(xlCellTypeConstants) '<-_| loop through its column "A" non blank cells
Set f = ws1Data.Find(what:=cell.value, LookIn:=xlValues, LookAt:=xlWhole) '<--| search for current cell value in Sheet1 data
If f Is Nothing Then '<--| if not found then...
Intersect(cell.EntireRow, .UsedRange).Interior.ColorIndex = 3 '<--| highlight current cell entire row
Else
For icol = 1 To .Range(cell, .Cells(cell.Row, .Columns.Count).End(xlToLeft)).Columns.Count - 1 '<--| loop through Sheet2 current cell row
If f.Offset(, icol) <> cell.Offset(, icol) Then '<--| if it doesn't match corresponding cell in Sheet1
cell.Offset(, icol).Interior.ColorIndex = 3 '<--| highlight Sheet2 not-matching cell
f.Offset(, icol).Interior.ColorIndex = 3 '<--| highlight Sheet1 not-matching cell
End If
Next icol
End If
Next cell
End With
End Sub

Define range based on the value of another cell

Is it possible to define a range in VBA based on a value given in a cell?
For example, I have a dataset with four columns and a constantly changing number of rows. I have the number of rows in cell F2. Suppose cell F2 indicates the number of rows is 385, then I be able to Range("A1:D385").Select, but I want the selection of the last cell to be dependent on cell F2.
So if I change F2 to 50, that the next time I run the macro, A1:D50 will be selected, but since I'm new to VBA I can't figure it out.
The most proper way to do this would be like this
Sub getRng()
Dim Cval As Variant
Dim Rng1 As Range
Cval = ActiveSheet.Range("F2").Value
Set Rng1 = ActiveSheet.Range("A1:D" & Cval)
End Sub
this sets Rng1 as an object that you can use later on in another function
such as
Rng1.Select
or
Rng1.Copy
This is what you are looking for:
Dim lastRow As Integer
With ThisWorkbook.Sheets(1)
lastRow = .Cells(.Rows.Count, "F").End(xlUp).row
.range("A1:D" & lastRow).Select
End With
The code looks for the first non-empty cell in column F, from bottom to top. Similar to selecting the last cell in column F and pressing Ctrl + up-arrow.

Find last cell with function output data and output new result

This problem uses the following data, which would be manually adaptive over a fixed cell range--with each cell in the B column range containing a formula. It aims to find the last data cell from the underlying formula cells.
I would like to find the last formula cell with data within the formula range B2:B11, and create a dynamic median from this last cell with the four cells above it. The median should be output to cell F6--result of 9. This is a dynamic exercise. Any thoughts on how to do this most efficiently, given the code below?
Sub OutputMedian()
Dim FunctionRange As Range
'Represents a fixed range with function in B2:B11
Set FunctionRange = Worksheets("Sheet1").Range("B2:B11")
'Must start median calc from B9, as it's the last cell with function output data
'Must store Median from last data cell, using 5 cell offset (see output from cell F2)
'Must output the Final (e.g., median output of 9 here) to cell F6
End Sub
See: Excel VBA: Get Last Cell Containing Data within Selected Range
My modified answer by #brettdj from above question (referred by #varocarbas). Thanks!
Got it to work!! Outputs the correct dynamic median, with five periods set from -4 Offset below.
Sub OutputMedian()
Dim WS As Worksheet
Dim rng1 As Range
Dim rng2 As Range
Set WS = Sheets("Sheet1")
Set rng1 = WS.Columns("B:B").Find("*", Range("B1"), xlValues, , xlByRows, xlPrevious)
Set rng2 = rng1.Offset(-4, 0)
Dim FirstCell As String
Dim LastCell As String
FirstCell = rng2.Address(0, 0)
LastCell = rng1.Address(0, 0)
Dim CellResponse As String
CellResponse = Evaluate("=median(" & FirstCell & ":" & LastCell & ")")
Range("F6").Value = CellResponse
End Sub
Better way to use objects (e.g., R1C1, Cells) in creating dynamic functions--i.e, without passing function into Evaluate as concatenated strings?

Find cells with same value within one column and return values from separate column of same row

I want to find all the cells in Column L with a particular value and return the values in Column D of the same row as those cells found.
So far, I am only able to return one result, which would be the top most result in my list, but I want to find all the rest as well, which I don't know the code to use.
Just to further explain: Value in cell D11 is the value I want to find in Column L of sheet "Master List". Supposedly I find the value in cells L13, L15 and L20, I want to return the value in cell D13, D15 and D20 into cells "C37:C39" of ws. Note: no. of cells that have the value may vary so the values returned will just appear from C37 downwards (something like automatic multiple selection, copy and paste)
Here's a little something to start the ball rolling:
Sub FindRelatedProducts()
Dim cell As Excel.Range
Dim D11Value As Variant
Dim D11Row As Variant
Dim ws As Worksheet: Set ws = Sheets("RShip")
Set cell = ws.Range("D11")
D11Value = cell.Value
With Sheets("Master List")
D11Row = Application.Match(D11Value, .Range("L:L"), 0)
If Not IsError(D11Row) Then
ws.Range("C37") = .Range("D" & D11Row).Value
End If
End With
End Sub
Here's an example using range variables.
You'll want to define a range for the input data range and a range for the output data. Then in the VBA you will want to change the wrk, inRng and outRng variables to be the named ranges you defined and change the column indexes in the for and if blocks to match the column index of the data you are looking for.
Option Explicit
Option Base 1
Sub FindValues()
Dim wrk As Worksheet
Dim inRng As Range
Dim outRng As Range
Dim cntr As Long
Dim outCntr As Long
Dim findVal As Double
Set wrk = Worksheets("Data")
Set inRng = wrk.Range("LookupRange")
Set outRng = wrk.Range("OutputRange")
' Clear the output range in case you have fewer values on this run than on the previous one
outRng.ClearContents
' Set the value you are looking for
findVal = 1
' Iterate through the rows in the input range. If you find the result you want then write it to the output range
For cntr = 1 To inRng.Rows.Count
If inRng(cntr, 1) = findVal Then ' Assumes the value you are finding is in column 1 of the input range
outRng(outCntr, 1) = inRng(cntr, 2) ' Assumes the values you are exporting is in column 2 of the input range
outCntr = outCntr + 1
End If
Next cntr
End Sub