Without using excel built-in filter or pivot table function, I want to extract some results using vba. Consider the following example: given data in coloumn A and B, I want to be able to input "a" in C1 and using the vba to get in Column D all the corresponding values from column B (1,3,5). If I input "b", I get 2, 6, so on. Thanks.

-
Not even an Excel formula?Siddharth Rout– Siddharth Rout2013-09-14 05:14:34 +00:00Commented Sep 14, 2013 at 5:14
3 Answers
Sub GenerateMatches()
With ActiveSheet
FinalRowA = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
InputLetter = ActiveSheet.Cells(1, 3)
NextRow = 1
For i = 1 To FinalRowA
If .Cells(i, 1) = InputLetter Then
.Cells(NextRow, 4) = .Cells(i, 2)
NextRow = NextRow + 1
End If
Next i
End With
End Sub
Obviously, you can make this alot more dynamic and faster, but this should get the job done.
1 Comment
Columns("D:D").Select Selection.ClearContentsEnter the following event macro in the worksheet code area:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim D1 As Range, K As Long
Dim N As Long, NN As Long
Set D1 = Range(Range("D1"), Range("D1").End(xlDown))
If Intersect(Target, Range("C1")) Is Nothing Then Exit Sub
Application.EnableEvents = False
v = Target.Value
K = 1
D1.Clear
NN = Cells(Rows.Count, "A").End(xlUp).Row
For N = 1 To NN
If v = Cells(N, "A").Value Then
Cells(K, "D").Value = Cells(N, "B").Value
K = K + 1
End If
Next
Application.EnableEvents = True
End Sub
Because it is worksheet code, it is very easy to install and automatic to use:
- right-click the tab name near the bottom of the Excel window
- select View Code - this brings up a VBE window
- paste the stuff in and close the VBE window
If you have any concerns, first try it on a trial worksheet.
If you save the workbook, the macro will be saved with it. If you are using a version of Excel later then 2003, you must save the file as .xlsm rather than .xlsx
To remove the macro:
- bring up the VBE windows as above
- clear the code out
- close the VBE window
To learn more about macros in general, see:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
and
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
To learn more about Event Macros (worksheet code), see:
http://www.mvps.org/dmcritchie/excel/event.htm
Macros must be enabled for this to work!
B.T.W.
You can do the same thing with formulas and no VBA - like VLOOKUP on steriods!
Comments
I understand when you say you didn't want to use filters or Pivots. But Formulas?
If something is possible with formulas then why VBA?
Paste this Array Formula in Cell D1 and press CTRL + SHIFT + ENTER and pull it down.
=IF(ISERROR(INDEX($A$1:$B$7,SMALL(IF($A$1:$A$7=$C$1,ROW($A$1:$A$7)),ROW(1:1)),2)),"",INDEX($A$1:$B$7,SMALL(IF($A$1:$A$7=$C$1,ROW($A$1:$A$7)),ROW(1:1)),2))
Screenshot
