Apologies if this is a duplicate, but I do not know how to word this correctly.
I have a workbook with 7 worksheets all named differently.
I want to write an if function that will search all the worksheets, and if it matches that criteria to paste into "Name" sheet. I have tried multiple ways and cannot achieve this. This is where I will get the criteria.
Dim Client As String
Client = InputBox("Enter the Clients name")
This code works if I extract data from one sheet:
Dim pasteRowIndex As Long
pasteRowIndex = 2
Dim LR as Long
LR = Cells(Rows.Count, 1).End(xlUp).Row
For I = 2 To LR
If Cells(I, 1).Value = Client Then
'Now the code to grab the data and past into a new workbook
Rows(I).Select 'This just works on the active sheet, but I want this to iterate through
all the sheets and paste the range into sheet2 in this code
Selection.Copy
'Switch to the sheet where you want to paste it & paste
Sheets("Sheet2").Select 'However I will change this name
Rows(pasteRowIndex).Select
ActiveSheet.Paste
'Next time you find a match, it will be pasted in a new row
pasteRowIndex = pasteRowIndex + 1
'Switch back to your table & continue to search for your criteria
'Sheets("Sheet1").Select
End If
Next I
While the above code works for a single sheet I want the macro to iterate through all the sheets, and they are not named Sheet1-Sheet7.
Also, there must be a cleaner way of doing this.
Apologies if this is unclear, do let me know if more clarity is required.
You may loop through all the sheets in your workbook as following sample code:
Dim Sht As Worksheet
For Each Sht In Worksheets
If Sht.Name <> "Sheet1" Or Sht.Name <> "Sheet7" Then
'Do your stuff here
'sample code to refer the row at specific sheet without activating it
Sht.Rows(I).Copy
Sheets("Sheet2").Cells(pasteRowIndex, 1).PasteSpecial xlPasteAll
End If
Next
Will recommend to avoid use of .Select and .Activate method. Instead use Worksheet variable to refer to the specific sheet.
Related
I have multiple workbooks running the same code, but behaving differently.
I think a user manually moved worksheets; changing the order.
The code uses
tempWs.Copy after:=ActiveWorkbook.Sheets(Worksheets.Count)
to copy a template sheet to the end of the workbook.
However, when running the following code in another module, the workbook seems to not recognize which sheet is the last sheet:
lastSh = ThisWorkbook.Worksheets.Count
....
ws.Cells(i,2).value = Worksheets(lastSh).Name
In some workbooks, the above code, as expected, returns the name of the last sheet (the newly created one).
In the workbooks with the odd behavior, lastSh points to the same sheet every time rather than recognizing I added another.
Another oddity: when I tried recreating the workbook by copying sheets from the erroring book to a new one, the error persists to that new version.
Why is the index of sheets seemingly stagnant or is my ".Copy after:=" doing something I don't know about?
Sub addToSummary()
Dim ws As Worksheet
Dim i, lastSh, lastRow As Long
Set ws = ThisWorkbook.Worksheets("Summary")
lastSh = ThisWorkbook.Worksheets.Count
lastRow = ws.Range("B6").End(xlDown).Row + 1
If ws.Cells(lastRow, 1).Value = "Total Amount Paid:" Then
Call addRow 'adds a row on a summary sheet if needed
ws.Cells(lastRow, 2).Value = Worksheets(lastSh).Name
Else
ws.Cells(lastRow, 2).Value = Worksheets(lastSh).Name
End If
ws.Cells(lastRow, 3).Formula = "='" + Worksheets(lastSh).Name + "'!currentPay"
End Sub
Regardless of creating a new file, this code is referencing the same sheet.
tempWs.Copy after:=ActiveWorkbook.Sheets(Worksheets.Count)
The number of sheets is not necessarily the same as the number of worksheets. If you have a chart sheet and 3 worksheets then Worksheets.Count is 3 but you have 4 Sheets so the sheet gets copied before the last sheet.
So you probably wanted this:
tempWs.Copy after:=ActiveWorkbook.WorkSheets(Worksheets.Count)
I am a new programmer when it comes to VBA and I am writing a code that scans multiple Criteria and then copy and pastes to another sheet. I have 2 Sheets right now Sheet1 and Sheet2, I will first need to scan J9 on Sheet1 and then lookup Sheet2 for Sheet1’s J9, afterwards I will pull everything with J9 in it from Sheet2 to Sheet1 with it starting at a specific Row, I’ve tried doing AutoFilter but as I am rarely new I believe that my code should be obsolete, please go easy on me. Many Thanks in advance! PS(I am using VBA 2013)
Sub tgr()
Dim wsData As Worksheet
Dim wsDest As Worksheet
Dim acrit() As String
Set wsData = Sheets("MaterialReport") 'Copying FROM this worksheet (it contains your data)
Set wsDest = Sheets("TIMINGBELTWPULLEY") 'Copying TO this worksheet (it is your destination)
'Populate your array of values to filter for
ReDim acrit(1 To 2)
acrit(1) = "TIMING"
acrit(2) = "PULLEY"
With wsData.Range("C1", wsData.Cells(wsData.Rows.Count, "C").End(xlUp))
.AutoFilter 1, aFruit, xlFilterValues 'Filter using the array, this avoids having to do a loop
'Copy the filtered data (except the header row) and paste it as values
.Offset(1).EntireRow.Copy
wsDest.Cells(wsDest.Rows.Count, "B29").End(xlUp).Offset(1).PasteSpecial xlPasteValues
Application.CutCopyMode = False 'Remove the CutCopy border
.AutoFilter 'Remove the filter
End With
This is my code that I’m working with, I’ve pulled it from a training site and edited it to my needs
I am trying to copy multiple columns from multiple worksheets into a new worksheet in Excel using a VBA Macro.
I have already created the worksheet, and I want to paste specific columns one after another in that worksheet.
I would like to copy from each worksheet all columns including and beyond a certain column, in all worksheets including and from Column F.
I have written a piece of code that selects the appropriate data and loops correctly.
However, i get a "run-time error 1004", when the loop hits a worksheet where I am copying only one column.
I know this is because of the choice of my code. However, I don't know how to solve the problem.
The problem is that my code selects a range to the end of the worksheet when there is only one column being selected. This creates a copied area too big to paste in the new worksheet.
Dim i As Integer
i = 1
Do While i <= Worksheets.Count - 1
Worksheets(i).Select
'Select, Copy and Paste Data
RangeFromF1
Selection.Copy
Worksheets("Combined").Select
Range("X1").Select
Selection.End(xlToLeft).Select
ActiveCell.Offset(0, 1).Select
ActiveSheet.Paste
i = i + 1
Loop
End Sub
Public Sub RangeFromF1()
Range("F1", Range("F1").End(xlDown).End(xlToRight)).Select
End Sub
Instead of going from column F to the right, try going from the last column to the left.
Public Sub RangeFromF1()
Range("F1", Cells(1, Columns.Count).End(xlToLeft).End(xlDown)).Select
End Sub
You might also want to get rid of all the Select stuff.
Sub CopyStuff()
Dim i As Long
i = 1
Do While i <= Worksheets.Count - 1
With Worksheets(i)
.Range("F1", .Cells(1, .Columns.Count).End(xlToLeft).End(xlDown)).Copy
Worksheets("Combined").Cells(1, Columns.Count).End(xlToLeft).Offset(, 1).Paste
i = i + 1
End With
Loop
End Sub
Before coming back to check for your answer noris, I figured out a way, to do as you suggested, with the following code:
Public Sub ReferenceSelection()
Dim startcell As Range
Set startcell = Range("A1").End(xlDown).End(xlToRight)
Range(startcell, ("F1")).Select
End Sub
I have a sheet which contains a column full of Item IDs called "Werkzeugtabelle Vormontage" and another sheet which contains part of the item IDs listed in sheet 1.
I want to filter Sheet 1 by the Item IDs that are similar to the ones in sheet 2. So basically have the sheet with more IDs chopped to the size of the sheet with less IDs. (Deleting the not similar ones would also be an option but no clue how that might work.)
If CheckSheet("BMV Vormontage") Then
Sheets("Werkzeugtabelle").Select
Sheets("Werkzeugtabelle").Copy After:=Sheets("BMV Vormontage")
ActiveSheet.Name = "Werkzeugtabelle Vormontage"
lRow = Cells(Rows.Count, 1).End(xlUp).Row
Sheets("Restanschluss Vormontage").Select
xRow = Cells(Rows.Count, 11).End(xlUp).Row
'CountUnique ("K3:K100")
'critCount = CountUnique.Count
For i = 3 To lRow
For a = 10 To xRow
Sheets("Werkzeugtabelle Vormontage").Cells(i, 1).AutoFilter Field:=1, Criteria1:=Sheets("Restanschluss Vormontage").Cells(a, 11).Value
Next a
Next i
End If
The CheckSheet is looking for that sheet to get a starting point in the workbook. "Werkzeugtabelle" is the non filtered vanilla sheet.
Whenever I have more than one similar Item ID between the two sheets, it won't show, because I am only looking for one criteria it seems.
I tried to do a loop.
Alright I guess I have found the solution. At least it does everything it does and doesn't spam me with error. Could you guys double check if this is a good code?
Sub Werkzeugtabelle_splitten()
Dim ws As Worksheet
Dim rng As Variant
Set ws = Sheets("Werkzeugtabelle")
' Splitten Vormontage
If CheckSheet("BMV Vormontage") Then
rng = Sheets("Restanschluss Vormontage").Range("K10:K100").Value
ws.Range("A3").AutoFilter _
Field:=1, _
Criteria1:=Application.Transpose(rng), _
Operator:=xlFilterValues
ws.Copy After:=Sheets("BMV Vormontage")
ActiveSheet.Name = "Werkzeugtabelle Vormontage"
ws.ShowAllData
End If
End Sub
So I have made that the orginial "Werkzeugtabelle" sheet will still exist and it only filters it > copies it to the right spot in the workbook and afterwards resets the filter on the original.
I am putting together a basic inventory control system and I would like the columns with a time-stamp in the "Checked-Out" column to be pasted into a list on another worksheet. I have successfully copied the correct entire rows, but I would like this to just copy and paste the table rows instead because I have instructions listed in column A that are not relevant for the compiled list. I am new to VBA coding, thanks in advance!
I have named ranges for the two tables called "Inventory_List": Inventory!$I$3:$N$1048576 and "Checked_Out": CheckedOut!$B$3:$G$1048576 as the copy/paste ranges respectively.
Sub testIt()
Dim r As Long, endRow As Long, pasteRowIndex As Long
endRow = 1000 ' of course it's best to retrieve the last used row number via a function
pasteRowIndex = 1
For r = 1 To endRow 'Loop through sheet1 and search for your criteria
If Cells(r, Columns("N").Column).Value > 0 Then 'Found
'Copy the current row
Rows(r).Select
Selection.Copy
'Switch to the sheet where you want to paste it & paste
Sheets("CheckedOut").Select
Rows(pasteRowIndex + 5).Select
ActiveSheet.Paste
'Next time you find a match, it will be pasted in a new row
pasteRowIndex = pasteRowIndex + 1
'Switch back to your table & continue to search for your criteria
Sheets("Inventory").Select
End If
Next r
End Sub
When I try to reference ranges instead of entire rows, I get "run-time error 1004" because my copy area and paste area aren't the same size, but I am a bit confused because my ranges seem to be the same size. I am pretty sure this is because I am adding the ranges to the incorrect portion of the code.
Copying and pasting of Excel ranges is quite standard, if you take into account 2 things:
Refer to the ranges correctly with the upper left cell and the lower right cell;
Always, refer to the Parent worksheet.
In the code below, the upper left cell and the lower right cells of the copied and pasted ranges are like this:
.Range(.Cells(count, 1), .Cells(count, "C"))
copyTo.Range(copyTo.Cells(count, 1), copyTo.Cells(count, "C"))
The parent worksheets are always referred. With with for the copyFrom and with explicit writing for copyTo.
Sub TestMe()
Dim copyFrom As Worksheet
Dim copyTo As Worksheet
Set copyFrom = Worksheets(1) 'Or better write the name - Worksheets("CheckedOut")
Set copyTo = Worksheets(2)
Dim count As Long
For count = 1 To 30
With copyFrom
If .Cells("N", count) > 0 Then
.Range(.Cells(count, 1), .Cells(count, "C")).Copy Destination:=copyTo.Range(copyTo.Cells(count, 1), copyTo.Cells(count, "C"))
End If
End With
Next
End Sub
Last, but not least - this is a must read for VBA - How to avoid using Select in Excel VBA