Loop over a column if a element of a list found do something in that row
Solution 1:
Here is an example that sets up both your source and the destination workbooks and shows you how to transfer the data between them. Plus some helpful tips below:
Option Explicit
Sub testme()
FindValues "Panel1_yes"
End Sub
Sub FindValues(ByVal value As String)
Dim srcWB As Workbook
Dim srcWS As Worksheet
Set srcWB = ThisWorkbook
Set srcWS = srcWB.Sheets("Sheet1")
Dim dstWB As Workbook
Dim dstWS As Worksheet
Set dstWB = ThisWorkbook '--- change to the new workbook
Set dstWS = dstWB.Sheets("Sheet2")
'--- find the end of the data in the destination sheet
Dim dstRow As Long
With dstWS
dstRow = .Cells(.Cells.Rows.Count, 1).End(xlUp).Row
End With
With srcWS
Dim lastRow As Long
lastRow = .Cells(.Cells.Rows.Count, 1).End(xlUp).Row
Dim i As Long
For i = 1 To lastRow
If IsInMyList(.Cells(i, 1).value) Then
dstRow = dstRow + 1
dstWS.Cells(dstRow, 1).value = .Cells(i, 1).value
dstWS.Cells(dstRow, 2).value = .Cells(i, 2).value & "_" & .Cells(i, 3).value
End If
Next i
End With
End Sub
Function IsInMyList(ByVal value As String) As Boolean
Dim theList() As String
theList = Split("Panel1,Panel1_yes,Panel2_yes", ",")
Dim item As Variant
For Each item In theList
If item = value Then
IsInMyList = True
Exit Function
End If
Next item
IsInMyList = False
End Function
Here are the good habits for your VBA code:
- Always use
Option Explicit
- Always be clear on what worksheet or range is being referenced
- Use intermediate variables (such as
lastRow
) to help yourself make your code more readable. Yes, it's a few extra lines of code. But in many instances it can make your code faster (if that's a concern), but you'll find readability will always be a bigger help to you in the long run.
Good luck!