Excel VBA Find last row number where column "C" contains a known value - excel

Seeking a method in Excel VBA to Find last row number where column "C" contains a known value.

This will find the last occurrence of happiness in column C
Sub SeekHappiness()
Dim C As Range, where As Range, whatt As String
whatt = "happiness"
Set C = Range("C:C")
Set where = C.Find(what:=whatt, after:=C(1), searchdirection:=xlPrevious)
MsgBox where.Address(0, 0)
End Sub
To output the row number only, use:
MsgBox Mid(where.Address(0, 0), 2)
To find the first occurrence:
Sub SeekHappiness()
Dim C As Range, where As Range, whatt As String
whatt = "happiness"
Set C = Range("C:C")
Set where = C.Find(what:=whatt, after:=C(1))
MsgBox where.Address(0, 0)
End Sub

You could loop through the column to find the last occurrence of a value.
Sub findLastRow()
Dim searchValue As String
Dim endRow As Integer
Dim lastRowSearchValue As Integer
searchValue = "testValue" ''enter your search value
With Worksheets("sheet1") ''enter the name of your worksheet
endRow = .Cells(Rows.Count, 3).End(xlUp).Row
For i = 1 To endRow
If .Cells(i, 3) = searchValue Then
lastRowSearchValue = i
End If
Next i
End With
End Sub
Just replace the value of the variable "searchValue" with whatever is the value you're looking for (maybe change the type of the variable if its not a string) and the Sub will store the index of the last row of the occurrence of the searchValue in the variable "lastRowSearchValue" for further use.

Sub GetRo()
'Either select data or replace selection with your range
Debug.Print Selection.Find(what:="mysring", searchdirection:=xlPrevious).Row
End Sub

Related

how to get last row that has velue Excel VBA within a range

I am new to VBA Macro. i just want to know how to get the last row that has value within a range
Set MyRange = Worksheets(strSheet).Range(strColumn & "1")
GetLastRow = Cells(Rows.Count, MyRange.Column).End(xlUp).Row
this code could find the last row for the whole sheet.. i just want it to find the last non null value cells
(
like in this case in the picture.. for the ("A8") range, the last row result should be ("A9:B9")
"A9:B9" cannot be last row... It is a range.
If you need such a range, but based on the last empty row, starting from a specific cell, you can use the next approach:
Sub testLastRowRange()
Dim sh As Worksheet, myRange As Range, lastRow As Long, strColumn As String
Dim lastCol As Long, endingRowRng As Range, strSheet As String
strSheet = ActiveSheet.Name 'please, use here your real sheet name
Set sh = Worksheets(strSheet)
strColumn = "A"
Set myRange = sh.Range(strColumn & 8)
lastRow = myRange.End(xlDown).row
lastCol = myRange.End(xlToRight).Column
Set endingRowRng = sh.Range(sh.Cells(lastRow, myRange.Column), sh.Cells(lastRow, lastCol))
Debug.Print endingRowRng.address
End Sub
For your specific example you could use CurrentRegion property.
This is based on the ActiveCell which is not generally advisable.
Sub x()
Dim r As Range
Set r = ActiveCell.CurrentRegion
MsgBox r.Address
End Sub

How can I place a formula in the first empty cell on Column F?

How can I place a formula in the first empty cell on Column F?
F3 is empty cell.
Need for that empty cell be =F2
Note: I'm looking for code to look for first empty cell F and I need to be able to insert in the first empty cell =F3.
Currently working with following code copied from here
Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
Dim currentRowValue As String
sourceCol = 6 'column F has a value of 6
rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row
'for every row, find the first blank cell and select it
For currentRow = 1 To rowCount
currentRowValue = Cells(currentRow, sourceCol).Value
If IsEmpty(currentRowValue) Or currentRowValue = "" Then
Cells(currentRow, sourceCol).Select
Exit For 'This is missing...
End If
Next
Your existing code implies you want to consider truely Empty cells and cells that contain an empty string (or a formula that returns an empty string) Note 1. (Given you simply copied that code from elsewhere, that may not be the case)
You can use End(xlDown) to locate the first truely Empty cell, or Match to locate the first "Empty" cell in a range (either just empty string, or either empty strings or Empty cells, in different forms)
If you want to find the first truely Empty cell, or cell containing an empty string:
Function FindFirstEmptyOrBlankCell(StartingAt As Range) As Range
Dim rng As Range
'Set search range
With StartingAt.Worksheet
Set rng = .Range(StartingAt, .Cells(.Rows.Count, StartingAt.Column).End(xlUp).Offset(1, 0))
End With
' Find first empty or blank cell
Set FindFirstEmptyOrBlankCell = rng.Cells(StartingAt.Worksheet.Evaluate("Match(True, " & rng.Address & "=""""" & ", 0)"), 1)
End Function
If you want to find the first truely Empty cell, and ignore cells containing an empty string:
Function FindFirstEmptyCell(StartingAt As Range) As Range
Dim rng As Range
'Set search range
With StartingAt.Worksheet
Set rng = .Range(StartingAt, .Cells(.Rows.Count, StartingAt.Column).End(xlUp).Offset(1, 0))
End With
' Find first empty cell
If IsEmpty(StartingAt.Cells(1, 1)) Then
Set FindFirstEmptyCell = rng.Cells(1, 1)
ElseIf IsEmpty(StartingAt.Cells(2, 1)) Then
Set FindFirstEmptyCell = rng.Cells(2, 1)
Else
Set FindFirstEmptyCell = rng.End(xlDown).Cells(2, 1)
End If
End Function
And for completeness, if you want to find the fisrt cell containing an empty string, and ignore truely Empty cells:
Function FindFirstBlankCell(StartingAt As Range) As Range
Dim rng As Range
Dim idx As Variant
'Set search range
With StartingAt.Worksheet
Set rng = .Range(StartingAt, .Cells(.Rows.Count, StartingAt.Column).End(xlUp).Offset(1, 0))
End With
' Find first blank cell
idx = Application.Match(vbNullString, rng, 0)
If IsError(idx) Then
'There are no Blank cells in the range. Add to end instead
Set FindFirstBlankCell = rng.Cells(rng.Rows.Count, 1)
Else
Set FindFirstBlankCell = rng.Cells(idx, 1)
End If
End Function
In all cases, call like this
Sub Demo()
Dim ws As Worksheet
Dim r As Range
Set ws = ActiveSheet '<~~~ or specify required sheet
Set r = FindFirstEmptyOrBlankCell(ws.Range("F3"))
' literally what was asked for
'r.Formula = "=F3"
' possibly what was actually wanted
r.Formula = "=" & r.Offset(-1, 0).Address(0, 0)
End Sub
Note 1
If IsEmpty(currentRowValue) Or currentRowValue = "" Then is actually redundant. Any value that returns TRUE for IsEmpty(currentRowValue) will also return TRUE of currentRowValue = "" (The reverse does not apply)
From comment can that same Fuction repeat until the last empty cel? I think this is what you mean is to continue to fill blank cells down through the used range
If so, try this
Sub Demo()
Dim ws As Worksheet
Dim cl As Range
Dim r As Range
Set ws = ActiveSheet '<~~~ or specify required sheet
Set cl = ws.Range("F3")
Do
Set r = FindFirstEmptyOrBlankCell(cl)
If r Is Nothing Then Exit Do
r.Formula = "=" & r.Offset(-1, 0).Address(0, 0)
Set cl = r.Offset(1, 0)
Loop
End Sub
Note, I've modified FindFirstEmptyOrBlankCell above to aloow it to return Nothing when it needs to:
Function FindFirstEmptyOrBlankCell(StartingAt As Range) As Range
Dim rng As Range
'Set search range
With StartingAt.Worksheet
Set rng = .Range(StartingAt, .Cells(.Rows.Count, StartingAt.Column).End(xlUp).Offset(1, 0))
End With
' Find first empty or blank cell
On Error Resume Next ' Allow function to return Nothing
Set FindFirstEmptyOrBlankCell = rng.Cells(StartingAt.Worksheet.Evaluate("Match(True, " & rng.Address & "=""""" & ", 0)"), 1)
End Function
You'll need to change your rowCount, the way you have it, the loop will stop before the first blank row. I believe you should just be able to set use .Formula for the empty cell. Hope this helps:
Sub EmptyCellFillFormula()
Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
Dim currentRowValue As String
sourceCol = 6 'column F has a value of 6
rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row + 1
For currentRow = 1 To rowCount
currentRowValue = Cells(currentRow, sourceCol).Value
If IsEmpty(currentRowValue) Or currentRowValue = "" Then
Cells(currentRow, sourceCol).Formula = "=F3"
End If
Next
End Sub

How to put the value of a match function in an offseted cell in VBA

I have two columns: I'm trying to loop through each one to find the word I put in the box. Following this, I want to write the respective row number in
the cell two cells to the left from the current cell. The activecell.offset just keeps giving me zero and I can't figure out what's going wrong
The jumps
quick Over
brown nine
fox lazy
dogs
Sub AddRow()
Dim i As Integer, j As Integer, HT As Variant, nr As Integer, nc As Integer, lrow As Integer, lrows As Variant, rng1 As Range, rng2 As Range, row As Integer, rows As Integer
nr = Selection.rows.Count
nc = Selection.Columns.Count
HT = InputBox("Enter column letter:")
Set rng1 = Range("E1:E100")
Set rng2 = Range("F1:F100")
For i = 1 To nr
For j = 1 To nc
If ActiveCell(i, j) = HT And ActiveCell.Column = 1 Then
lrow = Application.WorksheetFunction.Match(HT, Range("E1:E200"), 0)
Else
If ActiveCell(i, j) = HT And ActiveCell.Column = 2 Then
lrow = Application.WorksheetFunction.Match(HT, Range("F1:F200"), 0)
End If
ActiveCell.Offset(0,2).Value = lrow
End If
Next j
Next i
End Sub
Use Ranges instead.
QHarr's comment on your question is on track.
A Range represents a single cell or group of cells in an excel sheet, and it is the best way to address the cells in a worksheet.
You can address ranges by excel coordinates, eg. "A1" or by row number and column number.
Here is a quick example of getting a range, then using it to get information, or using it to move to other cells.
I included the correct use of Offset(). You can see now why QHarr said to use ranges, because you need a Range object to make Offset() work.
...oh, and Range.Value2 gives the value in a cell.
Option Explicit
Sub main()
Dim HT As String
Dim myRange As Range
Dim ColumnNumber As Integer
Dim myNewRange As Range
HT = InputBox("Enter column letter:")
'range returns a cell
Set myRange = Range(HT & "1")
'get the column of the cell.
ColumnNumber = myRange.Column
MsgBox ColumnNumber
'get the cell, one cell over and one cell down
Set myNewRange = myRange.Offset(1, 1)
MsgBox "My New Range is at " & myNewRange.Row & " - " & myNewRange.Column
End Sub

How to use range of column found using array as input and compare the range to a number to get output as "true" or "false" in a different column?

In the below code I found the column number of the values in the array. How to use that range to compare values to a with a variable?
Public Sub JpFee()
Dim rng As Range, rws As Long, w As Long, Str As Variant, Count As Integer, x(20) As Integer, Lt() As Variant, ht As Variant, Wdt As Variant, W8t As Variant
Dim row1, i, y As Integer
row1 = ActiveSheet.UsedRange.Rows.Count
MsgBox row1
Str = Array("length (cm)", "width (cm)", "height (cm)", "unit weight(kg)", "surface area L+W+H", "size")
For w = LBound(Str) To UBound(Str)
Set rng = Rows("1:1").Find(What:=Str(w), LookAt:=xlWhole, MatchCase:=False)
x(i) = rng.Column
i = i + 1
MsgBox rng.Column
Next w
End Sub
I would use a collection for something like this. You could also use a dictionary. (Whichever you prefer).
Here's an example of using a collection with what you're trying to do:
Sub tgr()
Dim ws As Worksheet
Dim HeaderCell As Range
Dim cHeaders As Collection
Set ws = ActiveWorkbook.ActiveSheet
Set cHeaders = New Collection
On Error Resume Next 'Collections will error if there are duplicates, this prevents that error
'Loop through each headercell
For Each HeaderCell In ws.Range("A1").CurrentRegion.Resize(1).Cells
'If the headercell contains text, add its column number to the collection and set the key to the headertext
If Len(HeaderCell.Text) > 0 Then cHeaders.Add HeaderCell.Column, CStr(HeaderCell.Text)
Next HeaderCell 'Advance the loop
On Error GoTo 0 'Clear the On Error Resume Next condition
'Now you can get the column number of a known header by referencing the header in your collection
'This will show the column number of the header "size"
'Note that the header does not need to be case sensitive, but must be the exact text
MsgBox cHeaders("size")
'So if you want to put in a value in the bottom row of a column:
ws.Cells(ws.Rows.Count, cHeaders("size")).End(xlUp).Offset(1).Value = 2
End Sub

Range of cells into single cell with carriage return

I am working through my first VBA book and would appreciate if someone would point me in the right direction. How would I transfer a range of rows into a single cell with carriage returns? I would then like to repeat this action for all ranges in the column.
I think I need to:
find the first cell with a value in the column
verify that the next row is not empty
find the last cell in the range
perform "the operation" on the range
Following up on my comments. here is a very simple way to achieve what you want.
Option Explicit
'~~> You can use any delimiter that you want
Const Delim = vbNewLine
Sub Sample()
Dim rngInput As Range, rngOutput As Range
Application.ScreenUpdating = False
Set rngInput = Range("A1:A5") '<~~ Input Range
Set rngOutput = Range("B1") '<~~ Output Range
Concatenate rngInput, rngOutput
Application.ScreenUpdating = True
End Sub
Sub Concatenate(rng1 As Range, rng2 As Range)
Dim cl As Range
Dim strOutPut As String
For Each cl In rng1
If strOutPut = "" Then
strOutPut = cl.Value
Else
strOutPut = strOutPut & Delim & cl.Value
End If
Next
rng2.Value = strOutPut
End Sub
Within the context of a worksheet-level code, the following will work. Column 2 is hard-coded, so you might want to pass in a value or otherwise modify it to fit your needs.
Dim rng As Range
Set rng = Me.Columns(2)
Dim row As Integer
row = 1
' Find first row with non-empty cell; bail out if first 100 rows empty
If IsEmpty(Me.Cells(1, 2)) Then
Do
row = row + 1
Loop Until IsEmpty(Me.Cells(row, 2)) = False Or row = 101
End If
If row = 101 Then Exit Sub
' We'll need to know the top row of the range later, so hold the value
Dim firstRow As Integer
firstRow = row
' Combine the text from each subsequent row until an empty cell is encountered
Dim result As String
Do
If result <> "" Then result = result & vbNewLine
result = result & Me.Cells(row, 2).Text
row = row + 1
Loop Until IsEmpty(Me.Cells(row, 2))
' Clear the content of the range
Set rng = Me.Range(Me.Cells(firstRow, 2), Me.Cells(row, 2))
rng.Clear
' Set the text in the first cell
Me.Cells(firstRow, 2).Value2 = result

Resources