excel 2007 macro select records
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 attemp开发者_如何学编程t at macros and not too sure how to begin.
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:
精彩评论