Recognizing New Sheet as Last - excel

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)

Related

Check sheets name based on a range, if sheet not found then create new sheet with name from range

I have a workbook with currently two sheets MI and Validation. Validation sheet column two have names, I need a code which should run ok opening the file and check if sheets are already created with all the names in column 2, for eg if there are 5 names from range B2:B7, then 5 sheets should be created, if sheet isn’t created then it should create new sheet with the name from name column. I tried few things but couldn’t succeeded, sorry can’t paste the code due to work Lap.
Tried vba code but can’t share due to work system.
You could loop through the worksheet-names in column 2 of the "Validation" sheet and run a check if a sheet with that name already exists In the workbook. If the sheet doesn't exist, you can use the .Add method of the "Sheets" object to create a new sheet with the name from the current cell in the loop.
Sub CreateSheets()
Dim wsValidation As Worksheet
Set wsValidation = ThisWorkbook.Sheets("Validation")
Dim lastRow As Long
lastRow = wsValidation.Cells(wsValidation.Rows.Count, 2).End(xlUp).Row
Dim sheetCount as Integer
sheetCount = ThisWorkbook.Sheets.Count
Dim i As Long
For i = 2 To lastRow
Dim sheetName As String
sheetName = wsValidation.Cells(i, 2).Value
If Not ThisWorkbook.Sheets(sheetName) Is Nothing Then
' sheet already exists, do nothing or add an action to do if it does
Else
' sheet doesn't exist, create it and add it after the last sheet
ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(sheetCount)).Name = sheetName
End If
Next i
End Sub

Copying Table Values to a New Sheet in a Loop?

So I've already had this piece of code tweaked on here for another reason. Searching through List Object Table's Column in For Loop
Essentially the issue at hand boils down to the fact that I want to loop through a table, and if a row meets certain criteria I want to copy the value over to a new tab (for later use.)
I've done this before by using a variable called RowToPastteTo to get to the next empty row and have followed the same structure as before, but or some reason all of the code runs without a debugging issue, but just doesn't copy the values over.
Here is the full code
Sub RequestedAssetList()
Dim FullAssLi As ListObject, RowRange As ListRow 'Defining the Table and Range
Set FullAssLi = ThisWorkbook.Sheets("Asset List").ListObjects("AssListTab") 'Set FullAsset Lists as the Asset Table
With ThisWorkbook 'Within the workbook
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Assets" 'Adds a sheet at the end of the workbook called Assets
End With
With ThisWorkbook.Sheets("Assets")
Dim RowToPasteTo As Long
'RowToPasteTo = ThisWorkbook.Worksheets("Assets").Range("A1").End(xlDown).Row + 1
RowToPasteTo = .Cells(.Rows.Count, "A").End(xlUp).Row + 1 'Sets variable as the next exmpy row on column A of Assets' tab
For Each RowRange In FullAssLi.ListRows
If RowRange.Range.Cells(9).Value = UserForm2.SourceLiBo.Value Then 'If Data Source matches userform criteria then
ThisWorkbook.Sheets("Assets").Range("A1").Value = RowRange.Range.Cells(2).Value
'
''
End If
Next
End With
End Sub
It seems that the problem line is If RowRange.Range.Cells(9).Value = UserForm2.SourceLiBo.Value Then
ThisWorkbook.Sheets("Assets").Range("A1").Value = RowRange.Range.Cells(2).Value
How can I get this to copy the figures from the FullAssL into the new Assets sheet?
I've played around, changing that line of code to changing the back ground colour of RowRange.Cells(9) and still nothing.
Your code has no errors, indeed. By the way, if i'm well thinking, you are pasting the value at the same cell ever. If you want a list of values, you have to increment your row reference like:
Dim i
i = 1
For Each RowRange In FullAssLi.ListRows
If RowRange.Range.Cells(9).Value = UserForm2.SourceLiBo.Value Then
ThisWorkbook.Sheets("Assets").Range("A" & i).Value = RowRange.Range.Cells(2).Value
i = i + 1
End If
Next

IF function data from multiple sheets paste into blank sheet VBA

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.

Copying data to a added worksheet

The code below adds a new worksheet to a summary workbook for every pagebreak in 2 other workbooks. I want to copy data from the other workbooks to each added sheet in the summary workbook. All of the data keeps copying only to sheet1. Thank you in advance for any help.
For n = 1 To Workbooks(file1name).Worksheets("Sheet1").HPageBreaks.Count
i = i + 1 'integer that tracks the pages being added
'SourceRange is a the range of data being copied
Set SourceRange = Workbooks(file1name).Worksheets("Sheet1").Range("A" & pgBreak, "Q" & Workbooks(file1name).Worksheets("Sheet1").HPageBreaks(n).Location.Row - 1)
SourceRange.Copy
summary.Sheets.Add 'summary is the summary workbook I would like to copy the data to
summary.Sheets(i).Activate
ActiveSheet.Paste
For j = 1 To Workbooks(file2name).Worksheets("Sheet1").HPageBreaks.Count
If matchVar = matchVar2 Then 'If the variable in workbook 1 matches the variable in workbook 2 than copy the information in between the page breaks
i = i + 1
Set SourceRange = Workbooks(file2name).Worksheets("Sheet1").Range("A" & pgBreak2, "Q" & Workbooks(file2name).Worksheets("Sheet1").HPageBreaks(j).Location.Row - 1)
SourceRange.Copy
summary.Sheets.Add
summary.Sheets(i).Activate
ActiveSheet.Paste
End If
Next
Excel adds the new sheet by default before active sheet, so your "Sheet1" is shifted each time you add a new sheet as that was the active one.
If you see the documentation of worksheet.add method you see that the newly created sheet is also activated, so don't need to activate it again, just paste your data ;)

listing text-based data from column C in multiple sheets into a single column in a master sheet in excel

I have a workbook filled with text-based data on several different sheets. All the sheets use the same headings, but have different text in the columns. I would like to be able to list the information contained in the column C from all of the sheets in a single column in a new sheet.
Is there a way to get all of that data into a single column without having to copy and past from nearly 100 different sheets?
Using VBA, here is a solution that works. You just need to insert a module into your workbook and run this. F11 > Insert > Module. Copy and paste this code, and hit play.
This will create a new worksheet with whatever name you define under newSheet. Then take the contents of EVERY worksheet Row C (after header), no matter how many you have or what their name is, and add them to the new one. I could see a problem if you exceed 1,000,000 rows.. Other than that, if there are any sheets you DON'T want to perform this on, we would add them as exceptions specifically by name in the If statement.
TESTED:
Private Sub CopyAllSheetsCol()
Dim WS As Worksheet
Dim newSheet As String
Dim lastRow As Long 'Last Row on source Sheet
Dim tRow As Long 'target row
newSheet = "Compiled" 'name can be changed here
Sheets.Add.Name = newSheet
tRow = 2 'Set the target Row to 2, Set the Header Row manually
For Each WS In ActiveWorkbook.Worksheets
If WS.Name <> newSheet Then 'Making sure we are only working with pre-existing sheets
lastRow = Sheets(WS.Name).Range("C2").End(xlDown).Row 'get last row of Column C on each Worksheet
For r = 2 To lastRow 'Loop through all rows skipping header
Sheets(newSheet).Cells(tRow, "C") = Sheets(WS.Name).Cells(r, "C") 'Copy to newSheet
tRow = tRow + 1 'Increment target row by 1
Next r
End If
Next
End Sub
edit: touched up explanation

Resources