Using the Find Function in VBA - excel

1
2
3
4
.
.
So I have a sequence of numbers running from 1-20. I have the number "1" on top selected and I would like to search the entire column and find the number "9". The code works when I don't name the range "rng"; it finds the number and selects. But the code stops working when I name the range of number. What's wrong with the range function? could it be that if I define Dim rng as Range that when I later define the "Set rng=" I cannot have the ".Select" or ".Copy" extension on the end?
Sub macro2()
Dim rng As Range
Set rng = Range(ActiveCell, ActiveCell.End(xlDown)).Select
rng.Find(10).Select
End Sub
Also, If I want to sum the entire column from 1-20, on the last cell below the number "20" should I use the following code? because the application object doesn't seem to do it. Thank you!
rng.End(xlDown).Offset(1, 0).Select
Application.WorksheetFunction.Sum (rng.Value)

To look for 10 in the active column you could try this (which ends up selecting the first 10 - although Select in vba isn't normally needed other than taken the user to location at code end)
test that the found range exists (ie you can find 10 before proceeding)
you should also use xlWhole to avoid matching 100 if the current default for [lookAt] is xlPart
using search [After] as Cells(1, ActiveCell.Column , and [Search Direction] as xlNext finds the first value looking down.
code
Sub QuickFind()
Dim rng1 As Range
Set rng1 = ActiveCell.EntireColumn.Find(10, Cells(1, ActiveCell.Column), xlFormulas, xlWhole, , xlNext)
If Not rng1 Is Nothing Then
Application.Goto rng1
Else
MsgBox "10 not found"
End If
End Sub
Part 2
Sub Other()
Dim rng1 As Range
Set rng1 = Range(Cells(1, ActiveCell.Column), Cells(Rows.Count, ActiveCell.Column).End(xlUp))
rng1.Cells(rng1.Cells.Count).Offset(1, 0) = Application.WorksheetFunction.Sum(rng1.Value)
End Sub

Try this, I hope this will help u to find the specific row no as well as column name too. In code you can use
strRw = FindColumn(Sheet name, "Value which need to be found", True, "Cell Name",Row number)
sourceCOL = colname(FindColumn(Shee Name, "Value which need to be found", False, , 4))
Below is main function of find
Public Function FindColumn(colnocountWS As Worksheet, srcstr As String, Optional rowflag As Boolean, Optional bycol As String, Optional strw As Integer, Optional stcol As Integer) As Integer
Dim srcrng As Range 'range of search text
Dim srcAddr As String 'address of search text
Dim stcolnm As String
colnocountWS.Activate
If stcol <> 0 Then stcolnm = colname(stcol)
If stcol = 0 Then stcolnm = "A"
If strw = 0 Then strw = 1
colnocountWS.Range(stcolnm & strw).Select
If ActiveSheet.Range(stcolnm & strw) = srcstr Then
ActiveSheet.Range(stcolnm & strw).Select
FindColumn = 1
Else
If bycol = "" Then
Set srcrng = colnocountWS.Cells.Find(Trim(srcstr), after:=ActiveCell, LookIn:=xlValues _
, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
Else
Set srcrng = colnocountWS.Cells.Find(Trim(srcstr), after:=ActiveCell, LookIn:=xlValues _
, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
End If
'ByPart
If srcrng Is Nothing Then
If bycol = "" Then
Set srcrng = colnocountWS.Cells.Find(Trim(srcstr), after:=ActiveCell, LookIn:=xlValues _
, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
Else
Set srcrng = colnocountWS.Cells.Find(Trim(srcstr), after:=ActiveCell, LookIn:=xlValues _
, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
End If
End If
If srcrng Is Nothing Then
FindColumn = 0
Exit Function
Else
srcAddr = srcrng.Address
colnocountWS.Range(srcAddr).Select
FindColumn = ActiveCell.Column
If rowflag = True Then FindColumn = ActiveCell.Row
End If
End If
End Function
'this function find column name
Public Function colname(iFinalCol1 As Integer) As String
Dim colnm As String
On Error GoTo gg
If Mid(Cells(1, iFinalCol1).Address, 3, 1) = "$" Then
colnm = Mid(Cells(1, iFinalCol1).Address, 2, 1)
Else
colnm = Mid(Cells(1, iFinalCol1).Address, 2, 2)
End If
gg: colname = colnm
End Function

Related

How to seperate and cut cells to the next one in Excel VBA?

I have a cell with ~230 characters (without space), and I would like to find '%' symbol in the cell then cut the rest of the cell and paste in the next cell to the bottom. Do it until all % found.
Sub test()
Dim c As Range
Range("B12").Select
i = 1
Set c = Selection.Find(What:="%", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not c Is Nothing Then
Do
c.Cut c.Offset(i, 0)
Set c = Selection.Find(What:="%", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
i = i + 1
Loop Until c Is Nothing
End If
End Sub
Using Split would be significantly easier. We can take the entire text into a String variable, then split it based on every occurrence of % and then output the array to the cells, skipping blanks and re-adding the % character.
Sub Example()
Dim InputRange As Range
Set InputRange = Range("B12")
Dim InputText As String
InputText = InputRange.Value
Dim TextArray() As String
TextArray = Split(InputText, "%")
Dim i As Long
For i = 0 To UBound(TextArray)
If TextArray(i) <> "" Then
InputRange = TextArray(i) & IIf(i <> UBound(TextArray), "%", "")
Set InputRange = InputRange.Offset(1, 0)
End If
Next
End Sub

Trying to find value in range and get its row. Variable not set error?

The code below is supposed to take the value for net in each month, copies it, search for net name in range1(another worksheet) and pastes value in the cell corresponding to that row and column "AA".
This part of code is having issue:
Set Netrng = Range("AA" & Range1.Find(What:=Net, After:=ActiveCell, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Rows.row)
The error is -
object variable or with block variable not set.
what am I doing wrong?
Sub test()
Dim Range2 As Range
Dim lRow As Long
Dim Count As Long
Dim Net As String
Dim Line As Range
Dim Netrng As Range
Dim First As Range
Dim Range1 As Range
Dim wb As Worksheet
Set First = ActiveCell
Set wb = ActiveSheet
Set Range1 = wb.Range(First, First.End(xlDown))
ActiveWindow.ActivatePrevious
ActiveSheet.PivotTables("PivotTable1").PivotFields("Client Code").CurrentPage _
= "BUN"
ActiveSheet.Range("B5").Activate
lRow = Cells(Rows.Count, 1).End(xlUp).row - 6
Set Range2 = Range(ActiveCell.Offset(2, -1), ActiveCell.Offset(lRow, -1))
Set Months = Range(ActiveCell.Offset(0, 0), ActiveCell.Offset(0, 2))
Count = 1
While Count <= Range2.Count
Set Line = Range2.Rows(Count)
Net = Line.Value
Line.Offset(0, 1).Copy
ActiveWindow.ActivatePrevious
Set Netrng = Range("AA" & Range1.Find(What:=Net, After:=ActiveCell, LookIn:=xlValues, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).row)
Netrng.Offset(0, 4).PasteSpecial Paste:=xlPasteValues
Netrng.Value = 0
ActiveWindow.ActivatePrevious
Line.Offset(0, 2).Copy
ActiveWindow.ActivatePrevious
Netrng.Offset(0, 8).PasteSpecial Paste:=xlPasteValues
ActiveWindow.ActivatePrevious
Count = Count + 1
Wend
End Sub
As is, the code is assuming that the Find is successful, which may not always be the case.
To test:
Dim foundRng as Range
Set foundRng = Range1.Find(What:=Net, After:=ActiveCell, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not FoundRng is Nothing Then
Set Netrng = Range("AA" & foundRng.Row)
...
End If
Other recommendations:
Avoid using Select and Activate. (and ActiveCell, ActiveWindow, anything Active).
Fully qualify which Workbook and Worksheet each Range is on (helpful reading in the answer on avoiding Select).
While...Wend is old-fashioned. Use a For Each loop.

Using Excel's find and searching by 2 strings

I need your help,
Is it possible to search an Excel spreadsheet based on 2 given values, as opposed to just 1? similar to that of an "AND" operator?
Here's what I have so far, but I guess if your looking for a needle in a hay stack:
Str = "apples" AND "oranges"
With Sheets(xSheet)
Set foundCell = .Cells.Find(What:=Str, After:=.Cells(1, 1), _
LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
The code below returns the wanted result:
Sub TestMe()
Dim str As String: str = "apples*oranges"
Dim foundCell As Range
Dim options As Variant
options = Array(str, Split(str, "*")(1) & "*" & Split(str, "*")(0))
Dim myVar As Variant
For Each myVar In options
With Worksheets(1)
Set foundCell = .Cells.Find(What:=myVar, After:=.Cells(1, 1), _
LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
If Not foundCell Is Nothing Then Exit For
Next myVar
If Not foundCell Is Nothing Then
Debug.Print foundCell.Address
End If
End Sub
We have two different strings that need to be seaerched for: "apples*oranges" and "oranges*apples". The split and the reverse is done pretty primitively:
options = Array(str, Split(str, "*")(1) & "*" & Split(str, "*")(0))
And then, using a For Each Loop with an early Exit For, the .Find() searches for the two strings.
Here is a simple loop alternative:
Sub ApplesAndOranges()
Dim r As Range, fruits As Range
Set fruits = Nothing
For Each r In ActiveSheet.UsedRange
v = r.Value
If v <> "" Then
If InStr(v, "apples") <> 0 And InStr(v, "oranges") <> 0 Then
If fruits Is Nothing Then
Set fruits = r
Else
Set fruits = Union(fruits, r)
End If
End If
End If
Next
MsgBox fruits.Address(0, 0)
End Sub
From the example, you see it returns all cells that contain both sub-strings.

How to get cell address from Find function in Excel VBA

How do I get cell address using Find function.
Here's the code
Dim Found As Range
Set Found = Worksheets("Sheet 1").Cells.Find(What:="test", LookAt:=xlWhole, MatchCase:=True)
If Not Found Is Nothing Then
' do something
End If
When I debug the code, "Found" variable contain a "string" instead of cell address.
It seems you can just use found.address even though it shows as string. The below code worked for me.
Sub findCellAddress()
Dim ra As Range
Set ra = Cells.Find(What:="fff", LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False)
If ra Is Nothing Then
MsgBox ("Not found")
Else
MsgBox (ra.Address)
End If
End Sub
I could not find this anywhere on the internet.
This code will give you the row and the column.
Dim ThisPos As Range
With Range("A1:J100")
Set ThisPos = .Find(What:="List_Position", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not ThisPos Is Nothing Then
Cell_Add = Split(ThisPos.Address, "$")
ThisRow = Cell_Add(1)
ThisCol = Cell_Add(2)
End If
End With
This code will give you reference style of the cell address.
Dim SValue As Range
With Range("D1:D100")
Set SValue = .Find(What:="Searched Value", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not SValue Is Nothing Then
Cell_Split_R = Split(SValue.Address(ReferenceStyle:=xlR1C1), "R")
Cell_Split_C = Split(Cell_Split_R(1), "C")
SCol = Cell_Split_C(0)
SRow = Cell_Split_C(1)
End If
End With

VBA Identify numbers within a range

I am sure this is a simple one but cant seem to find anything explicit out on the WWW.
I need my code to identify any numbers between 1 and 9 within a column for it to throw the error back for that range, I can only get it working with one number at present.
Public Sub ErrorCheck()
Dim FindString As String
Dim Rng As Range
FindString = ""
If VBA.Trim(FindString) <> "" Then
With Sheets("Scoring").Range("S:S")
Set Rng = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
MsgBox "Error", True
Else
End If
End With
End If
End Sub
Thanks for your help!
You can execute your code iteratively for all the values you want. Example:
Public Sub ErrorCheck()
Dim FindString As String
Dim Rng As Range
Dim startVal As Integer, endVal As Integer
startVal = 1
endVal = 9
For i = startVal To endVal
FindString = CStr(i)
With Sheets("Scoring").Range("S:S")
Set Rng = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
MsgBox "Error", True
Exit For
Else
End If
End With
Next i
End Sub

Resources