Excel Inserting Function Columns Utilizing a Macro - vba

I would like is a macro that after every 4 rows it inserts a function column which for row 3 down will include a function and rows 1 & 2 would be identical to the previous one and row 3 would say Planned orders.
I would like to add this identical macro to create every 5 after this one, then one for every 6 and one for every 7.
It can be 4 macros I just have to click in the right order not anything to fancy.
I created the macro below which inserts a row every 4th column, but I have to move the table over three columns to begin with and it doesn't generate the last column. How could I get the functions I want added to this column?
Sub insert_column_after_interval_4()
Dim iLastCol As Integer
iLastCol = Cells(1, Columns.Count).End(xlToLeft).Column ' same as CTRL+RIGHT ARROW
For colx = 5 To iLastCol Step 5
Columns(colx).Insert Shift:=xlToRight
Next
End Sub
Picture included for how the table currently looks, the end result would be just 4 additional formula columns after that and after every subsequent 4 columns in the spreadsheet.

The code below will insert 3 Columns after every fourth Column, the first column will be added into the sixth Column and then from there after every four columns there will be three columns inserted.
The data from the last two columns in the set of four columns will be pasted into the fist two columns of the new columns.
Two things to remember. You always want to use direct referencing to WorkBooks WorkSheets to avoid confusion in the program when multiple WorkBooks and WorkSheets are available.
Option Explicit
Sub InsertingColumns()
'Always want to directly reference the WorkBook and WorkSheet which contains your data
'Change Book1 and Sheet1 as per your requirement
Dim CurrentWorkSheet As Worksheet
Set CurrentWorkSheet = Workbooks("Book1").Worksheets("Sheet1")
Dim LastColumn As Long
LastColumn = CurrentWorkSheet.Cells(1, Columns.Count).End(xlToLeft).Column
'Step 7 to cater for the every forth Column plus the 7 columns being added
'Started at 6 because "After every four columns" means the fith Column and catering for the Cal Day in Column 1
Dim CurrentColumn As Long
For CurrentColumn = 6 To LastColumn Step 7
'Current Column to CurrentColumn + 2 will have 3 Cells selected
CurrentWorkSheet.Range(Cells(1, CurrentColumn), Cells(1, CurrentColumn + 2)).Insert Shift:=xlToRight
'Copy Data from the second column from the right and paste into the first new column
CurrentWorkSheet.Columns(CurrentColumn - 2).Copy
CurrentWorkSheet.Columns(CurrentColumn).PasteSpecial Paste:=xlPasteValues
'Copy Data from the first column from the right and paste into the second new column
CurrentWorkSheet.Columns(CurrentColumn - 1).Copy
CurrentWorkSheet.Columns(CurrentColumn + 1).PasteSpecial Paste:=xlPasteValues
Next CurrentColumn
End Sub
See BEFORE and AFTER Below:
For the 5, 6 and 7 inserts you can then just edit this four insert loop to cater for the others.

Related

How copy first and last column data of 3 pivot tables and put grand total in next columns

step 1 - copy first and last column data of first pivot table and paste it in same sheet (Say A61, B61).
step 2 - Copy first and last column date of second pivot table and past it below data of first table. Grand total column should go to next column (Say A65, C65)
step 3 - Copy first and last column date of third pivot table and past it below data of second table. Grand total column should go to next column (Say A70, D65)
I have written the code half way through
Sub Pivotcopy()
Dim pt As PivotTable
Dim s1 As Worksheet
Dim Lastrow As Long
Set s1 = Sheets("EDP Defaulter")
Set pt = ActiveSheet.PivotTables("PivotTable6")
With pt.TableRange2
Union(.Columns(1), .Columns(.Columns.Count)).Copy
End With
s1.Range("A61").PasteSpecial Paste:=xlPasteValues
s1.Rows("61:65").EntireRow.Delete
Set pt = ActiveSheet.PivotTables("PivotTable7")
With pt.TableRange2
Union(.Columns(1), .Columns(.Columns.Count)).Copy
End With
Lastrow = s1.Range("A61:A" & Rows.Count).End(xlDown).Row
s1.Range("A" & Lastrow - 1).PasteSpecial Paste:=xlPasteValues
End Sub
I need help in pasting the second table data in column C. As the command above copies and place it in column A and B

Loop through column values from one sheet and paste COUNTIF value from another column into another sheet

I have two sheets in an Excel file and need to perform a COUNTIF formula from one sheet and paste the respective information in another sheet. The original sheet just has the type in 1st column with an empty 2nd column. I am trying to loop through the Type from Sheet 1, in each increment loop through the Type from Sheet 2, and past the Count of column 2 from Sheet 2 into Column 2 of sheet 1.
My current VBA code is as follows:
Sub TestOE()
'For loop to go until end of filled cells in 1st column of each sheet
a = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
b = Worksheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
'Loop
For i = 2 To a
For j = 2 To b
If Worksheets("Sheet1").Cells(i, 1).Value = Worksheets("Sheet2").Cells(j, 1).Value Then
Worksheets("Sheet1").Cells(i, 2).Value = Application.WorksheetFunction.CountIf(Range("B:B"), 1)
End If
Next j
Next i
End Sub
This code is only pasting 0's in the desired outcome on Sheet 1.
Sheet to extract information from
Sheet to paste information in
Desired Outcome in destination sheet
You can simply use sumif function to sum the values based on criteria.
here is the formula
=COUNTIF(Sheet1!$A$2:$A$20,Sheet2!A2)
if you want to sum the col B then
=SUMIF(Sheet1!$A$2:$A$20,Sheet2!A2,Sheet1!$B$2:$B$20)
In a few steps, you can accomplish what you want without VBA, and just use a pivot table. Just do as follows.
Select your data set, including the header.
Click on insert tab, then PivotTable. See example for Office 365
Since you want a different worksheet, set PivotTable to be "New Worksheet" See example.
You'll need to drag the TYPE field into the rows, and binary into the values. CountIF is the same as summing binary, so you can leave as sum. See Example
And you'll have an output nearly identical to what you're looking for:

VBA - IF loop improvements

I'm currently running a macro which identifies duplicates in a workbook, however it identifies the first set off the index and doesn't tag the first set then which has led to me setting up a if statement to by pass this, which adds duplicate to the first instance too. This is taking a long time to do however and would like to improve this, if possible. Any suggestions would be greatly appreciated, I am new to VBA but have been learning bits as I've encountered new problems!
'Declaring the lastRow variable as Long to store the last row value in the Column1
Dim lastRow As Long
'matchFoundIndex is to store the match index values of the given value
Dim matchFoundIndex As Long
'iCntr is to loop through all the records in the column 1 using For loop
Dim iCntr As Long
Dim first_dup As Long
Dim tagging As Long
Dim item_code As String
'Finding the last row in the Column 1
lastRow = Range("B1000000").End(xlUp).Row
'
'looping through the column1
For iCntr = 2 To lastRow
'checking if the cell is having any item, skipping if it is blank.
If Cells(iCntr, 1) <> "" Then
'getting match index number for the value of the cell
matchFoundIndex = WorksheetFunction.Match(Cells(iCntr, 1), Range("A1:A" & lastRow), 0)
'if the match index is not equals to current row number, then it is a duplicate value
If iCntr <> matchFoundIndex Then
'Printing the label in the column B
Cells(iCntr, 4) = "Duplicate"
End If
End If
Next
For first_dup = 2 To lastRow
If Cells(first_dup, 5) = "Duplicate" Then
item_code = Cells(first_dup, 1)
For tagging = 2 To lastRow
If Cells(tagging, 1) = item_code Then
Cells(tagging, 5) = "Duplicate"
End If
Next
End If
Next
Example data:
item code
1
2
3
4
1 duplicate
2 duplicate
3 duplicate
4 duplicate
1 duplicate
2 duplicate
3 duplicate
4 duplicate
My first suggestion is not to over-complicate things, try using duplicate values conditional formatting to see if this helps:
Failing that, if you are desperate to find ONLY the duplicates, and not the first occurrence, you can use a formula like this: (In Cell B2 if your Data starts in A2, it will require a header row that doesn't match, or your first row will always match)
=IF(COUNTIF($A1:A$1,A2)>=1,"Duplicate","")
Which when pasted down your row of data could look something like this:
There are also VBA solutions if you are desperate for a VBA solution, but I thought I'd give you the simple ones first. Let me know how you get on in the comments.
Edit: you can just insert the above formula using VBA, with R1C1 notation, e.g.:
Sub test()
Range("B2:B" & Range("A1").End(xlDown).Row).FormulaR1C1 = "=IF(COUNTIF(R1C1:R[-1]C1,RC1)>=1,""Duplicate"","""")"
End Sub
I'll break this down so you know what is happening.
Range("B2:B" & Range("A1").End(xlDown).Row) selects the cells in column B between B2 and the last filled row in column A i.e. Range("A1").End(xlDown).Row (so this won't work if you expect blanks in column A as part of your data)
Then, it sets the R1C1 ref formula to "=IF(COUNTIF(R1C1:R[-1]C1,RC1)>=1,""Duplicate"","""")", where R1C1 means first row, first column, (i.e. $A$1)
R[-1]C1 means previous row, first column. For example,
If you are in B5, this would select A4.
If you are in A2, this would select A1.
If you are in A1, this would error out because you cant be in a row earlier than 1.
And RC1 means current row, first column.
Hope this helps!
The answer was the same as the initial code I presented, it's taking roughly 5 minutes for 30000 items so it isn't too bad at what it does.

Select multiple rows in excel based on last row

I have a piece of code which selects the entire row from my table based on the last data in column K. E.g. if I have rows 5 to 10 populated, it will select row 10.
How do I get the code to select multiple rows from row 5 all the way to the last row as defined below?
Thanks
Sub selectlastrow()
Dim lastrow As Long
Dim report As Worksheet
Set report = Excel.ActiveSheet
Sheets("Risks").Select
lastrow = Range("K5:K48").End(xlDown).Row
report.Cells(lastrow, 2).EntireRow.Select
End Sub
To follow up:
I'm stuck on how to structure a piece of code that:
Loops through all worksheets that begin with the number 673: (e.g. 673:green, 673:blue)
Selects the data in these worksheets from row 5 up until the last row with data - code that works for this is
With report
.Range(.Cells(5, "K"), .Cells(.Rows.Count, "K").End(xlUp)).EntireRow.Select
End With
Select the "Colours" worksheet
Paste the rows at the next available blank row. There could be up to 40/50 worksheets which will have data pasted into the "Colours" worksheet so I need the data added to the next available line.
Thank you in advance.
Use a cell reference that combines both the Range object and Range.Cells property.
with report
.Range(.Cells(5, "K"), .Cells(.rows.count, "K").End(xlUp)).EntireRow.Select
end with
You have multiple ways to select a range of rows. Easiest based on available data you have:
report.Range("K5").resize(lastrow - 4).EntireRow.Select
Report.Range("B5:B" & lastrow).EntireRow.Select
Depending on what you're actually doing with your code, just replace the expression inside of rowRange.
Dim rowRange As Range
Set rowRange = Range("a1:A8").Rows.EntireRow
rowRange.Select
Voila!

Sumif across multiple sheets, specific rows and columns

I have 20 sheets (let's say three, for simplicity) and I need to sumif each of those sheets against one main tab with all the data in it. Each sheet is for a different business entity but each sheet has the same format:
Format: Business 1000
Format: Business 2000
I will insert monthly data into the DATA tab and will need a macro to go into Sheet 1, 2, 3 etc. and run a sumif against the DATA tab matching column B (business unit code). I will also have this run for each month so Row3 will have Actual or Forecast.
The problem:
DATA tab gets deleted and reset with next month's data, therefore all sumifs must change into values.
not all rows are equal, some may have 5-6 items and then a Sum for the total, eg: travel may include hotel, parking, meals, car rental. So SumIF can only run where column B has a code. Otherwise do NOTHING.
I don't know how to code a relative reference inside sumif. I can VBA code a column and tell it to enter "Text" into each non-blank cell. Although I can't tell it to change or have relative cell data.
Then for next month (when data tab gets reset) the next column must be filled in. If it's simpler I can add another row with an X in the active month's column, so the macro can check if there is an X in that row, then do the sum if for that column.
It's simple to run a sum if, copy paste to all non blank rows, and then recopy as value only. But not when I have 20+ sheets, and need to do that every month.
Ok, so here is an example of what you want to do. In this example, I have left it up to you to set in the code which column you are looking to fill this month.
Change the value of Const ColumnNumber = 4 to change the column you are filling this month 4=D, 5=E etc (Apologies I only work in R1C1 ref style).
FirstRow always appears to be 4, but I have left that there in case you need to change it.
Worksheetfunction.sumif takes parameters in the same order as the normal sumif, so I am passing in column 1 of the data sheet for the range, cell c of the same row as the criteria, and column 2 of the data sheet as the sum range.
Using worksheetfunction.sumif will return the value to the cell, not the formula so that solves your problem of the data sheet being deleted and recreated.
I have also left the option for you to fill in the green rows with something else.
Const ColumnNumber = 4
Const FirstRow = 4
Sub LoopSomeSheets()
Dim sht As Worksheet
'go through each sheet in the workbook
For Each sht In ThisWorkbook.Sheets
'ignore the sheet named "data"
If sht.Name <> "data" Then
Dim LastRow As Long
'figure out where the sheet ends
LastRow = sht.cells.SpecialCells(xlCellTypeLastCell).Row
'variable to sum totals
Dim RunningTotal as Double
For i = FirstRow To LastRow
If sht.Cells(i, 3).value = "SUM" Then
'Put the total value in the sum cell
sht.Cells(i, ColumnNumber).value = RunningTotal
'reset the total for the next group
RunningTotal = 0
Else
Dim SumOfData as Double
'get the sumif value
SumOfData = _
WorksheetFunction.SumIf(Sheets("data").Columns(1), sht.Cells(i, 2), Sheets("data").Columns(2))
'add to the running total
RunningTotal = RunningTotal + SumOfData
'then update the cell
sht.Cells(i, ColumnNumber).value = SumOfData
End If
Next i
End If
Next sht
End Sub