Lookup Value in Same Column on Multiple Worksheets - excel

In column B on three (Bakery, Floral, Grocery) of the five sheets in my workbook, I want to find rows that have the word Flyer in column B. There will be multiple rows in each worksheet that have the word Flyer in column B. When it finds the word Flyer, it will paste the entire row into Sheet1.
I go this to work on one tab, but want the same code to search all three tabs (but NOT all five ... this is the issue) and paste all of the rows with the word Flyer in column B into Sheet1.
My code (works, but only on the Bakery tab):
Sub CopyRowsFlyer()
'This looks in the Bakery tab and moves everything that has "Flyer" in column B to Sheet 1
Dim bottomB As Integer
Dim x As Integer
bottomB = Sheets("Bakery").Range("B" & Rows.Count).End(xlUp).Row: x = 1
Dim c As Range
For Each c In Sheets("Bakery").Range("B3:B" & bottomB)
If c.Value = "Flyer" Then
c.EntireRow.Copy Worksheets("sheet1").Range("A" & x)
x = x + 1
End If
Next c
End Sub

Similar to other solutions posted. Pretty simple. Replaces bounding for range checking. Fewest variables. No mid-execution dimensioning.
Sub CopyRowsFlyer()
Dim strSh As Variant, c As Range, x As Integer
x = 1
For Each strSh In Array("Bakery", "Floral", "Grocery")
For Each c In Worksheets(strSh).Range("B:B")
If c = "" and c.Row > 2 Then
Exit For
ElseIf c = "Flyer" and c.Row > 2 Then
c.EntireRow.Copy Worksheets("Sheet1").Range("A" & x)
x = x + 1
End If
Next
Next
End Sub

You just want to loop through the three sheets you want. Try this:
Sub CopyRowsFlyer()
'This looks in the Bakery tab and moves everything that has "Flyer" in column B to Sheet 1
Dim bottomB As Integer
Dim x As Integer
Dim SheetsArray() As Variant
Dim ws As WorkSheet
Dim i As Integer
SheetsArray = Array("Bakery", "Sheet2Name", "Sheet3Name")
For i = LBound(SheetsArray) To UBound(SheetsArray)
Set ws = Sheets(SheetsArray(i))
bottomB = ws.Range("B" & Rows.Count).End(xlUp).Row: x = 1
Dim c As Range
For Each c In ws.Range("B3:B" & bottomB)
If c.Value = "Flyer" Then
c.EntireRow.Copy Worksheets("sheet1").Range("A" & x)
x = x + 1
End If
Next c
Next i
End Sub

You can substitute an element of a string array for the ID in Sheets.
Here is your code modified to reflect.
Sub CopyRowsFlyer()
Dim bottomB As Integer
Dim x As Integer
Dim sheetName(1 to 3) As String, i as Integer
sheetName(1) = "Bakery"
sheetName(2) = "Floral"
sheetName(3) = "Grocery"
x=1
For i = 1 to 3
bottomB = Sheets(sheetName(i)).Range("B" & Rows.Count).End(xlUp).Row
Dim c As Range
For Each c In Sheets(sheetName(i)).Range("B3:B" & bottomB)
If c.Value = "Flyer" Then
c.EntireRow.Copy Worksheets("sheet1").Range("A" & x)
x = x + 1
End If
Next c
Next i
End Sub

Store the desired worksheet names in an array and loop through them.
Sub CopyRowsFlyer()
Dim bottomB As Long, b As Long, x As Long
Dim w As Long, vWSs As Variant
vWSs = Array("Bakery", "Floral", "Grocery")
x = 1
For w = LBound(vWSs) To UBound(vWSs)
With Worksheets(vWSs(w))
bottomB = .Range("B" & Rows.Count).End(xlUp).Row
For b = 3 To bottomB
If LCase(.Cells(b, "B").Value) = "flyer" Then
.Rows(b).EntireRow.Copy Worksheets("sheet1").Range("A" & x)
x = x + 1
End If
Next b
End With
Next w
End Sub
While this method of looping through the cells in each worksheet's column B is considered inefficient compared to other methods like the .Range.Find method, it will not make a lot of difference on smaller sets of data. If you have a large number of rows on each worksheet to examine, you may wish to explore other more direct avenues of retrieving the information.

Related

Looping from the last row in one sheet to the first row in the next sheet

I'm trying to copy/paste values from multiple sheets into one.
I have the loop down but the macro overwrites the values in the same column where the data is being written.
Sub Main()
MedRT_EPC Sheets("Chemical Structure (14)")
MedRT_EPC Sheets("Enzymes (19)")
MedRT_EPC Sheets("Diuretics (5)")
MedRT_EPC Sheets("Imaging Agents (12)")
MedRT_EPC Sheets("Vitamins (27)")
End Sub
Sub MedRT_EPC(ws As Worksheet)
' Copy EPC cells Macro
Dim bottomL As Integer
Dim x As Integer
bottomL = ws.Range("I" & Rows.Count).End(xlUp).Row: x = 1
Dim c As Range
For Each c In ws.Range("I:I" & bottomI)
If c.Value = "EPC" Then
c.EntireRow.Copy Worksheets("sheet4").Range("A" & x)
x = x + 1
End If
Next c
End Sub
I've tried adding this:
Dim LastTargetRow As Long
' code here
With ws
LastTargetRow = .Range("I" & Rows.Count).End(xlUp).Row + 1
End With
' code here
As I said above, Autofilter would be quicker (or using Find) but if you stick with a loop, the main thing is not to start each worksheet at row 1 for your paste range.
Sub MedRT_EPC(ws As Worksheet)
' Copy EPC cells Macro
Dim bottomL As Long, x As Long
bottomL = ws.Range("I" & Rows.Count).End(xlUp).Row
Dim c As Range
For Each c In ws.Range("I2:I" & bottomL) 'or I1 as applicable
If c.Value = "EPC" Then
x = Worksheets("sheet4").Range("I" & Rows.Count).End(xlUp).Row + 1
c.EntireRow.Copy Worksheets("sheet4").Range("A" & x)
End If
Next c
End Sub
Your issue is that the "x" does not change. Try the below code. Fill the x1, x2, x3, x4, and x5 with the numbers you want.
Sub Main()
MedRT_EPC Sheets("Chemical Structure (14)",x1)
MedRT_EPC Sheets("Enzymes (19)",x2)
MedRT_EPC Sheets("Diuretics (5)",x3)
MedRT_EPC Sheets("Imaging Agents (12)",x4)
MedRT_EPC Sheets("Vitamins (27)"x5)
End Sub
Sub MedRT_EPC(ws As Worksheet, x as Integer)
' Copy EPC cells Macro
Dim bottomL As Integer
bottomL = ws.Range("I" & Rows.Count).End(xlUp).Row: x = 1
Dim c As Range
For Each c In ws.Range("I:I" & bottomI)
If c.Value = "EPC" Then
c.EntireRow.Copy Worksheets("sheet4").Range("A" & x)
End If
Next c
End Sub

Need help copy/pasting in Excel VBA from one workbook to another

I need to find out how to write some basic code that will take each cell's value (which will be an ID number) from a selected range, then match it to a cell in a master workbook, copy said cell's entire row, then insert it into the original document in place of the ID number. Here's the kicker: certain ID numbers may match with several items, and all items that have that number must be inserted back into the document. Here's an example:
Master Document Workbook
A B C D A B C D
1 a ab ac 2
2 b bc bd 3
2 b be bf
3 c cd de
I would select the cells containing 2 and 3 in the Workbook, which after running the code would give me this:
Workbook
A B C D
2 b bc bd
2 b be bf
3 c cd de
Here's what I have going on so far but it's a total mess. The only thing it's managed to successfully do is store the selected range in the Workbook I want to paste to. It won't compile past that because I don't understand much of the syntax in VBA:
Sub NewTest()
Dim rng As Range
Dim FirstRow As Range
Dim CurrentCol As String
Dim FirstRowVal As Integer
Dim CurrentColVal As Variant
Dim rngOffset As Range
CurrentCol = "Blah"
Set FirstRow = Application.InputBox("Select the row containing your first raw material", Type:=8)
FirstRowVal = FirstRow.Row
Set rng = (Application.InputBox("Select the cells containing your IC numbers", "Obtain Materials", Type:=8))
Set rngOffset = rng.Offset(0, FirstRowVal)
CurrentColVal = rng.Column
Call CopyPaste
End Sub
Sub CopyPaste()
Dim Blah As Range
Set x = Workbooks.Open("Workbook Path")
Workbooks.Open("Workbook Path").Activate
Set y = Workbooks.Open("Master Path")
Workbooks.Open("Master Path").Activate
With x
For Each Cell In rng
x.Find(rng.Cell.Value).Select
If Selection.Offset(0, -1) = Selection Then
Selection.EntireRow.Copy
Selection = Selection.Offset(0, -1)
Else
Selection.EntireRow.Copy
Blah = Selection
End If
Workbooks.Open("Workbook Path").Activate
Sheets("Formula Sheet").Select
Blah.Insert (rng.Cell)
End
Sheets("sheetname").Cells.Select
Range("A1").PasteSpecial
'Sheets("sheetname").PasteSpecial
.Close
End With
With x
.Close
End With
End Sub
Would very much appreciate anyone who could help point me in the right direction. Thanks.
I'll bite, you can use the output array to populate any range on any worksheet.
Sub FindAndMatch()
Dim arrMatchFrom() As Variant, arrMatchTo() As Variant, arrOutput() As Variant
Dim i As Integer, j As Integer, counter As Integer
counter = 0
arrMatchFrom = Range("A2:D6")
arrMatchTo = Range("G2:G3")
For i = LBound(arrMatchTo, 1) To UBound(arrMatchTo, 1)
For j = LBound(arrMatchFrom, 1) To UBound(arrMatchFrom, 1)
If arrMatchTo(i, 1) = arrMatchFrom(j, 1) Then
counter = counter + 1
ReDim Preserve arrOutput(4, counter)
arrOutput(1, counter) = arrMatchTo(i, 1)
arrOutput(2, counter) = arrMatchFrom(j, 2)
arrOutput(3, counter) = arrMatchFrom(j, 3)
arrOutput(4, counter) = arrMatchFrom(j, 4)
End If
Next
Next
For i = 1 To counter
For j = 1 To 4
Debug.Print arrOutput(j, i)
Cells(9 + i, j) = arrOutput(j, i)
Next
Next
End Sub

Excel VBA find match and return alternating values

I am having trouble trying to include something into a macro I am building. I need it to search through column C
for cells that say "start trans" and in one column over (d)- the first value will be equal to zero, next instance should be 100, next instance 0 next instance 100 so on until the end of the data.
Instances are not always every 4th line and I have other zeros that I want it to overlook.
Thank you for any help!
How about this one:
Sub GoGoGo()
Dim l As Long: Dim i As Long
Dim b As Boolean
With ActiveSheet
l = .Cells(.Rows.Count, "C").End(xlUp).Row
For i = 5 To l
If .Cells(i, "C").Value2 = "start trans" Then .Cells(i, "D").Value2 = b * -100: b = Not b
Next i
End With
End Sub
Try this.
Sub test()
Dim rngDB As Range, rng As Range
Dim n As Long, Result As Integer
Set rngDB = Range("c5", Range("c" & Rows.Count).End(xlUp))
For Each rng In rngDB
If rng = "start trans" Then
n = n + 1
If n Mod 2 Then
Result = 0
Else
Result = 100
End If
rng.Offset(0, 1) = Result
End If
Next rng
End Sub

Applying a formula to multiple columns, across multiple sheets in Excel

I am trying to apply the =LOWERCASE() formula to four columns (J, O, T, and Y) across multiple sheets in the same workbook.
Here's the VBA code I have so far, it is applying to the right columns, but it's returning an error for each.
Sub Clean_Lowercase()
Const N As Integer = 1
Dim r As Long, i As Integer, X As Integer, t As Long
Dim rng As Range, r As Range
Dim v As Variant
v = Array("J", "O", "T", "Y")
t = 1
For i = 1 To Sheets.Count - 1
r = Sheets(i).UsedRange.Rows.Count
For X = 0 To UBound(v)
Set rng = Sheets(i).Range(v(X) & N & ":" & v(X) & r)
For Each r In rng
r.Formula = "=LOWERCASE()"
Next
Next
End Sub
I am very new to VBA coding, any suggestions is greatly appreciated! I really want to learn.
Many thanks!
There are several problems with this.
You are using the r twice, once as a Long, once az a Range.
The For Each loop's Next is missing
The formula needs a reference of what would you like to set to lowercase.
For example, if you want to have the lowercase value of the left neightbouring cells, you should write: =LOWERCASE(R[1]C[-1])
Sheets are a 1 based collection, so if you write For i = 1 To Sheets.Count - 1, the last sheet wont be processed (maybe this is intentional?) and the code will throw an error at the first sheet (no sheets(0) exist)
Something like this works:
Sub Clean_Lowercase()
Const N As Integer = 1
Dim r As Long, i As Integer, X As Integer, t As Long
Dim rng As Range, ri As Range
Dim v As Variant
v = Array("J", "O", "T", "Y")
t = 1
For i = 1 To Sheets.Count
r = Sheets(i).UsedRange.Rows.Count
For X = 0 To UBound(v)
Set rng = Sheets(i).Range(v(X) & N & ":" & v(X) & r)
For Each ri In rng
ri.Formula = "=LOWERCASE(R[1]C[-1])"
Next
Next
Next
End Sub

Copy three columns into one column in Excel VBA

I need help to create a Excel VBA macro. I have a workbook contains 4 worksheets. Coulmn "A" in worksheet number 1, 2 and 3 are filled with data. I need to copy these data into Sheet 4 Column "A". I already done this by using this code but it dosn't work (it only copy the data by replacing ..).
EXAMPLE (I need to do following)
(Sheet 1 Col. A)
1
2
3
4
(Sheet 2 Col. A)
5
6
(Sheet 3 Col. A)
7
8
9
Need to copy all above in sheet 4 Col. A as follows
1
2
3
4
5
6
7
8
9
So, I wrote a code as follows
Sub CopyColumnToWorkbook()
Dim sourceColumn As Range, targetColumn As Range
Set sourceColumn = Worksheets("Sheet1").Columns("A")
Set targetColumn = Worksheets("Sheet4").Columns("A")
sourceColumn.Copy Destination:=targetColumn
End Sub
Sub CopyColumnToWorkbook2()
Dim sourceColumn As Range, targetColumn As Range
Set sourceColumn = Worksheets("Sheet2").Columns("A")
Set targetColumn = Worksheets("Sheet4").Columns("A")
sourceColumn.Copy Destination:=targetColumn
End Sub
Sub CopyColumnToWorkbook2()
Dim sourceColumn As Range, targetColumn As Range
Set sourceColumn = Worksheets("Sheet3").Columns("A")
Set targetColumn = Worksheets("Sheet4").Columns("A")
sourceColumn.Copy Destination:=targetColumn
End Sub
This above coding is not work as I need. Someone please help me to do as in above EXAMPLE.
Thank you very much.
This is quick code I threw together just to get you on the right track. It can be cleaned up. Basically you want to look through each sheet and see what the last column used is, then copy the entire used range for column A, and paste it onto the master sheet, starting from the last cell used in column A. You don't want to paste entire columns, so I used "End(xlUp)" which find the last cell used in column A.
Sub ColumnAMaster()
Dim lastRow As Long, lastRowMaster As Long
Dim ws As Worksheet
Dim Master As Worksheet
Application.ScreenUpdating = False
Set Master = Sheets.Add
Master.Name = "Master"
lastRowMaster = 1
For Each ws In ThisWorkbook.Sheets
If ws.Name <> "Master" Then
lastRow = ws.Range("A" & Rows.Count).End(xlUp).Row
ws.Range("A1:A" & lastRow).Copy Destination:=Master.Range("A" & lastRowMaster)
lastRowMaster = Master.Range("A" & Rows.Count).End(xlUp).Row + 1
End If
Next
Application.ScreenUpdating = True
MsgBox "Done!"
End Sub
Sorry StackOverflow is not indenting the code as it should...
Things you may want to do: check if there is any data at all inside each sheet before copying A over to the master, loop through worksheets in a specific order, check if a 'master' sheet exists or not already, etc.
Here is another way, very quick and basic but does the job
You could obviously combine all of those 3 do loops into one loop
Dim x As Integer
Dim y As Integer
x = 1
y = 1
Do Until Worksheets("Sheet1").Range("A" & x) = ""
Worksheets("Sheet4").Range("A" & y) = Worksheets("Sheet1").Range("A" & x)
y = y + 1
x = x + 1
Loop
x = 1
Do Until Worksheets("Sheet2").Range("A" & x) = ""
Worksheets("Sheet4").Range("A" & y) = Worksheets("Sheet2").Range("A" & x)
y = y + 1
x = x + 1
Loop
x = 1
Do Until Worksheets("Sheet3").Range("A" & x) = ""
Worksheets("Sheet4").Range("A" & y) = Worksheets("Sheet3").Range("A" & x)
y = y + 1
x = x + 1
Loop

Resources