I have the following VBA code:
Sub test(): Dim NameValue As String, w1 As Worksheet, w2 As Worksheet Dim i As Long, j As Long, k As Long, c As Long Set w1 = Sheets("Sheet2"): Set w2 = Sheets("Sheet3") GetNameValue: For i = 1 To w1.Range("A" & Rows.Count).End(xlUp).row If w1.Range("A" & i) = "NAME:" Then If InStr(1, NameValue, w1.Range("B" & i)) Then GoTo GetNext j = i + 1: Do Until w1.Range("A" & j) = "DATE OF BIRTH:": j = j + 1: Loop NameValue = Trim(NameValue & " " & w1.Range("B" & i) & "|" & w1.Range("B" & j)) c = c + 1: End If GetNext: Next i: NameValue = NameValue & " " For k = 1 To c i = InStr(1, NameValue, "|"): j = InStr(i, NameValue, " ") w2.Range("A" & k) = Left(NameValue, i - 1): w2.Range("B" & k) = Mid(NameValue, i + 1, j - i) NameValue = Mid(NameValue, j + 1, Len(NameValue) - j) Next k End Sub
To break this code:
1) Define the first sheet to be found and the second sheet (output sheet) to which the results should be added.
2) Find the first column for the specific row "NAME:" and once we find the value in the second column, put it in the output sheet, look for "DATE ββOF BIRTH:". After "DATE ββOF BIRTH:" is found, put it next to "NAME:" in the output sheet.
3) Repeat until there are no more entries.
I am sure that this is a very simple modification, but what I would like to do is check if a certain line exists if it captures the record directly BELOW it, and then continue to search for the next line and the record associated with it, as well as the code.
Can someone point me to what I will need to change in order to do this (and, preferably, why)?
In addition, how can I extend this code to run multiple sheets when submitting results on one sheet? Do I need to adjust the range that goes through the sheets w_1 .... w_ (n-1) (with the output sheet w_n, possibly in another book)?
Remote line continuations in code:
Sub test() Dim NameValue As String, w1 As Worksheet, w2 As Worksheet Dim i As Long, j As Long, k As Long, c As Long Set w1 = Sheets("Sheet2") Set w2 = Sheets("Sheet3") GetNameValue: For i = 1 To w1.Range("A" & Rows.Count).End(xlUp).Row If w1.Range("A" & i) = "NAME:" Then If InStr(1, NameValue, w1.Range("B" & i)) Then GoTo GetNext j = i + 1 Do Until w1.Range("A" & j) = "DATE OF BIRTH:" j = j + 1 Loop NameValue = Trim(NameValue & " " & w1.Range("B" & i) & "|" & w1.Range("B" & j)) c = c + 1 End If GetNext: Next i NameValue = NameValue & " " For k = 1 To c i = InStr(1, NameValue, "|") j = InStr(i, NameValue, " ") w2.Range("A" & k) = Left(NameValue, i - 1) w2.Range("B" & k) = Mid(NameValue, i + 1, j - i) NameValue = Mid(NameValue, j + 1, Len(NameValue) - j) Next k End Sub
UPDATE: just to make sure we're all on the same page about what the output will look like. Suppose we are looking for the entry below A and the entry next to C:
INPUT A 1 B y 3 z 4 tds 7 C 8 A 1 Z y 3 z 4 tds 7 C 12 OUTPUT B 8 Z 12 . . .