2
votes

I have a reference set of data in a column of cells (it could have been a row, but whatever).

I want to go through several worksheets, checking a selected range of values and if the current cell value is in the reference data, use it as the value to paste into an Offset of the next series of cells until the current cell has changed to some new value in the reference data, at which time the paste process should repeat for the new value and next series of cells. e.g.

Sub doStuff()
Dim RefRange As Range, queryRange As Range, checkCell As Rnage
String pasteDate As String

Set RefRange = Range("A1:A50")
Set queryRange = .Selected

For Each checkCell In queryRange
  If checkCell.Value IN RefRange <***here's where I don't know what to use ***>
     pasteData = checkCell.Value
     ' Advance to next item
     Next
  ElseIf checkCell.Value Not In queryRange <***here's where I don't know what to use ***>
     ActiveCell.Offset(0,+1).Value = pasteData
  End If
Next
End Sub

I know how to do this in SQL, is there some similar method in VBA?

In SQL:

Select a, b from table where c in ('foo', 'bar', 'baz') OR

Select a, b from table where c in (select e from some_other_table)

TIA

1
See VBA help for .Find method.Jean-François Corbett
Hey JCF, why not post a short answer for the credit?:)brettdj

1 Answers

1
votes

I doubt there will be a need to loop through all the data simply use a formula in the entire column and replace with the resulting value. Like this:

Sub Test()

    With ActiveSheet.UsedRange.Columns(3).Offset(1)
        .Formula = "=IF(ISERROR(MATCH(B2,A:A,0)),"""",B2)"
        .Value = .Value
    End With

End Sub

The code above looks at all values in the B column to test for a match in the A column. If match is found then the B column value is displayed in the c column. If no match is found it displays a blank cell but you can change that to whatever you want.

enter image description here