I would like to write a macro in vb to select all rows where values in column B contain the characters 'via'. This is my first attempt at macros and not too sure how to begin.
+1
A:
This one should do it for you (it worked for me) - code adapted from here.
Option Explicit
Sub SelectByValue(Rng1 As Range, Value As String)
Dim MyRange As Range
Dim Cell As Object
'Check every cell in the range for matching criteria.
For Each Cell In Rng1
If InStr(1, Cell.Text, "via") Then
If MyRange Is Nothing Then
Set MyRange = Range(Cell.Address)
Else
Set MyRange = Union(MyRange, Range(Cell.Address))
End If
End If
Next
'Select the new range of only matching criteria
MyRange.Select
End Sub
Sub CallSelectByValue()
'Call the macro and pass all the required variables to it.
'In the line below, change the Range and the Value as needed
Call SelectByValue(Range("B1:B10"), "via")
End Sub
How to use it?
- Copy the code above.
- Open the workbook in which you would like to run this code.
- Press Alt + F11 to open the Visual Basic Editor (or VBE).
- From the menu, choose Insert-Module.
- Paste the code into the code window at right.
- Change the Call SelectByValue(Range("B1:B10"),"via") line in the code to match your needs.
- Close the VBE.
How to test the code?
- Hit Tools-Macro-Macros and double-click CallSelectByValue.
Before running the Macro:
After running the Macro:
Leniel Macaferi
2010-09-02 19:53:13
Thanks for the detailed response, really appreciate it. Onemore thing, how would I display or cut the rows into another worksheet
vbNewbie
2010-09-02 20:27:17