Copy paste stopped working after upgrade to 365 - excel

Hi I have bit of a code that has worked for a long time but it no longer works, we have recently been upgraded to 365, The code filers data on one worksheet then copies and paste into another worksheet but the paste no longer works. I am new to this so any help is much appreciated.
Thanks in advance.
This is the bit of code which is part of a longer module
Application.StatusBar = "GENERATE LIST OF LICENSES DUE TO EXPIRE"
Sheets("due to expire").Select
Columns("A:I").Select
Selection.ClearContents
Sheets("Import").Select
Range("B1").Select
Selection.AutoFilter
Dim lngStart As Long, lngEnd As Long
lngStart = Range("M1").Value 'assume this is the start date
lngEnd = Range("P1").Value 'assume this is the end date
Range("a1:I5000").AutoFilter field:=9, _
Criteria1:=">=" & lngStart, _
Operator:=xlAnd, _
Criteria2:="<=" & lngEnd
Range("a1:i5000").Select
Selection.Copy
Sheets("due to expire").Select
Range("a1").Select
ActiveSheet.PasteSpecial
Cells.EntireColumn.AutoFit
Number_of_Records = Sheets("Main").Range("L7").Value + 2
Selection_Range = Number_of_Records & ":1000000"
Rows(Selection_Range).Select
Selection.Delete Shift:=xlUp
Number_of_Records = Sheets("Main").Range("L7").Value + 1
Selection_Range = "J2:J" & Number_of_Records
Range("J2").Select
Selection.AutoFill Destination:=Range(Selection_Range)
Sheets("Import").Select
Range("B1").Select
Selection.AutoFilter
Range("C1").Select
Selection.AutoFilter

It could be the date format has changed so add a message box to check.
Sub DueToExpire()
Application.StatusBar = "GENERATE LIST OF LICENSES DUE TO EXPIRE"
Dim wsImport As Worksheet, wsDue As Worksheet
Dim lngStart As Long, lngEnd As Long
Set wsDue = Sheets("due to expire")
With wsDue
.Columns("A:I").ClearContents
End With
Set wsImport = Sheets("Import")
With wsImport
lngStart = .Range("M1").Value 'assume this is the start date
lngEnd = .Range("P1").Value 'assume this is the end date
MsgBox "Start date is " & Format(lngStart, "d mmm yyyy") & vbLf & _
"End date is " & Format(lngEnd, "d mmm yyyy")
With .Range("A1:I5000")
.AutoFilter Field:=9, Criteria1:=">=" & lngStart, _
Operator:=xlAnd, Criteria2:="<=" & lngEnd
.Copy
wsDue.Range("A1").PasteSpecial
.AutoFilter Field:=9
End With
End With
Number_of_Records = Sheets("Main").Range("L7").Value + 2
MsgBox "Number of records = " & Number_of_Records
With wsDue
.Rows(Number_of_Records & ":1000000").Delete Shift:=xlUp
.Range("J2").AutoFill Destination:=.Range("J2:J" & Number_of_Records - 1)
.Columns.AutoFit
End With
Application.StatusBar = ""
End Sub

Related

To add the excel formulas into VBA Macro with condition

I have recorded some formulas into Macros and they are functioning properly, however I am not able to update them so that they should select the range themselves where the data ends in the last end in Column C. These 3 formulas extracts Date, File Name and Status of Files from Column A. As you see for now the range is e.g. "F3 to F313" where next time if the Data in Column C is up to C500 Range than I have to manually copy and paste the formulas. Is there anyway these 3 formulas should automatically detect the last text cell from Column C and ends there. That would be much helpful.
To Extract Date
Sub Macro13() 'To Extract Date
ActiveCell.FormulaR1C1 = "=extractDate(RC[-1])"
Range("D2").Select
Selection.Copy
Range("D3:D313").Select
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub
To Find Status of File
Sub Macro15() 'To Find Status of File
ActiveCell.FormulaR1C1 = _
"=IFERROR(LOOKUP(2^15,SEARCH({""Feed"",""Feed 1"",""Feed 2""},RC[-3]),{""Feed"",""Feed 1"",""Feed 2""}),""Combine"")"
Range("F2").Select
Selection.Copy
Range("F3:F313").Select
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub
To extract File Name
Sub Macro17() 'To extract File Name
ActiveCell.FormulaR1C1 = _
"=IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""ABCD - GAMA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+2),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""ALPHA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+2),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9," & _
"0},RC[-2]&""1234567890""))-1))=""ABCD - BETA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+8),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""DBETA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+8),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""A"",LEFT(RC[-2]," & _
"MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+6),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))="""",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+8),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""ABETA"",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+6),LEF" & _
"T(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2] & ""1234567890""))-1))))))))"
Range("E2").Select
Selection.Copy
Range("E3:E313").Select
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub
Try this:
Sub TestThis()
Dim LastRow As Long, ws As Worksheet
Set ws = ActiveSheet
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
ws.Range("D2:D" & LastRow).FormulaR1C1 = "=extractDate(RC[-1])"
ws.Range("F2:F" & LastRow).FormulaR1C1 = "=IFERROR(LOOKUP(2^15,SEARCH({""Feed"",""Feed 1"",""Feed 2""},RC[-3]),{""Feed"",""Feed 1"",""Feed 2""}),""Combine"")"
ws.Range("E2:E" & LastRow).FormulaR1C1 = _
"=IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""ABCD - GAMA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+2),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""ALPHA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+2),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9," & _
"0},RC[-2]&""1234567890""))-1))=""ABCD - BETA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+8),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""DBETA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+8),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""A"",LEFT(RC[-2]," & _
"MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+6),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))="""",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+8),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""ABETA"",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+6),LEF" & _
"T(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2] & ""1234567890""))-1))))))))"
End Sub

Activesheet shifting away from original sheet on second iteration of the substatement

I can run this program one iteration at a time, but when I let it run on the next i, the VarCellValues come back as values from a different sheet. What would be causing the active sheet to change away from the workbook and first sheet the macro is opened from?
Sub copy_financials_2022()
'
' copy_financials_2022 Macro
'
Dim i As Integer
Dim VarCellValue As String
Dim VarCellValue2 As String
Dim VarCellValue3 As String
Dim VarCellValue4 As String
Dim VarCellValue5 As String
Dim currwbk As Workbook
Set currwbk = ThisWorkbook
For i = Range("A2").Value To Range("C2").Value
Set currwbk = ThisWorkbook
VarCellValue = Range("B" & i).Value
VarCellValue2 = Range("C" & i).Value
VarCellValue3 = Range("A" & i).Value
VarCellValue4 = Range("D" & i).Value
VarCellValue5 = Range("E" & i).Value
Application.DisplayAlerts = False
Workbooks.Open (Range("A3").Value & VarCellValue4 & ".xlsx")
'Workbooks.Open ("S:\Finance\_2022 FINANCIAL REPORTS\National Financials\09-30\CONSOLIDATED MONTHLY FINANCIAL STATEMENT" & ".xlsm")
'Workbooks.Open (Range("B3").Value & VarCellValue4)
Workbooks(VarCellValue4).Activate
'inserted "Sheets(VarCellValue5).Activate" below after the third tab was active on Los Angeles Sheet (should have been the first tab)
Sheets(VarCellValue5).Activate
Sheets(VarCellValue5).Unprotect Password:="forecast22"
Columns("A:S").Select
Selection.EntireColumn.Hidden = False
Workbooks.Open ("S:\Finance\_2022 FINANCIAL REPORTS\National Financials\09-30\CONSOLIDATED MONTHLY FINANCIAL STATEMENT" & ".xlsm")
Sheets(VarCellValue2).Activate
Range("A6:Q6").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range("A6:Q88").Select
Selection.Copy
Workbooks(VarCellValue4).Activate
Range("A6").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("B:B,D:E,G:G,I:J,L:N,K:K").Select
Range("K1").Activate
Selection.EntireColumn.Hidden = True
Range("C7").Select
'Range("A6").Select
Application.CutCopyMode = False
ActiveWorkbook.Save
Range("C7").Select
ActiveCell.FormulaR1C1 = "Sept MTD"
Range("H7").Select
ActiveCell.FormulaR1C1 = "Sept YTD"
Range("S8").Select
ActiveCell.FormulaR1C1 = "Aug - Dec 2021"
Range("A6").Select
ActiveSheet.Protect Password:="forecast22"
ActiveWorkbook.Save
ActiveWindow.Close
'Workbooks.Close ("S:\Finance\_2022 FINANCIAL REPORTS\National Financials\05-31\CONSOLIDATED MONTHLY FINANCIAL STATEMENT" & ".xlsm")
Next i
End Sub
Instead of relying on a sheet being active, fully qualify each Range call with the appropriate workbook/worksheet.
Dim currwbk As Workbook
Set currwbk = ThisWorkbook
Dim currWs As Worksheet
Set currWs = currwbk.ActiveSheet
For i = currWs.Range("A2").Value To currWs.Range("C2").Value
VarCellValue = currWs.Range("B" & i).Value
VarCellValue2 = currWs.Range("C" & i).Value
VarCellValue3 = currWs.Range("A" & i).Value
VarCellValue4 = currWs.Range("D" & i).Value
VarCellValue5 = currWs.Range("E" & i).Value
Dim wb As Workbook
Set wb = Workbooks.Open(currWs.Range("A3").Value & VarCellValue4 & ".xlsx")
With wb.Worksheets(VarCellValue5)
.Unprotect Password:="forecast22"
.Columns("A:S").Hidden = False
' and so on
End With
Next

Error when saving a new file using SaveAs function in vba

I am accepting a date from Input Box and filtering my data and saving it in a new workbook. When I am saving this new workbook, its giving me a Run-time error 1004 with a sentence as:
Method 'SaveAs'of object'_Workbook' failed.
I am unable to find a solution to this.
Sub GIACTSDS121()
Dim dte As Date
mBox = InputBox("Enter a date")
If IsDate(mBox) Then
dte = CDate(mBox)
Dim Lastrow As Long
Lastrow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
ActiveSheet.Range("A1:AC" & Lastrow).AutoFilter Field:=2, Criteria1:=">=" & dte, _
Operator:=xlAnd, Criteria2:="<" & dte + 1
Range("U1").Select
ActiveSheet.Range("A1:AC" & Lastrow).AutoFilter Field:=21, Criteria1:="Yes"
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
ActiveSheet.Range("A:A,E:E,I:I,M:N,Q:T,X:Z").EntireColumn.Delete
ActiveWorkbook.SaveAs Filename:="K:\K_Drive\RP\RPS-Metrics-ops\' Operations Metrics\Investigation Documentation\GIACT Investigations\SDS_Cases\_" & dte & ".xlsx", FileFormat:=51
ActiveWorkbook.Close
Else
MsgBox "This is not a date. Please try again"
End If
End Sub
The Filename parameter passed to SaveAs contains an invalid character that windows does not accept for a filename
Filename:="K:\K_Drive\RP\RPS-Metrics-ops\' Operations
^
|
maybe this is the cause!
Get rid of all ActiveSheet, ActiveWorkbook and all .Select if possible (see How to avoid using Select in Excel VBA).
Also specify a worksheet for every object that is located in a worksheet like Range, Cells, Rows, Columns.
Public Sub GIACTSDS121()
Dim ws As Worksheet
Set ws = ActiveSheet 'better define by name as: Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim mBox As Variant
mBox = InputBox("Enter a date")
If IsDate(mBox) Then
Dim dte As Date
dte = CDate(mBox)
Dim LastRow As Long
LastRow = ActiveSheet.Range("A" & ws.Rows.Count).End(xlUp).Row
ws.Range("A1:AC" & LastRow).AutoFilter Field:=2, Criteria1:=">=" & dte, _
Operator:=xlAnd, Criteria2:="<" & dte + 1
ws.Range("A1:AC" & LastRow).AutoFilter Field:=21, Criteria1:="Yes"
ws.Range(ws.Range("A1"), ws.Range("A1").End(xlDown).End(xlToRight)).Copy
Dim NewWb As Workbook
Set NewWb = Workbooks.Add
NewWb.Worksheets(1).Paste
NewWb.Worksheets(1).Range("A:A,E:E,I:I,M:N,Q:T,X:Z").EntireColumn.Delete
NewWb.SaveAs Filename:="K:\K_Drive\RP\RPS-Metrics-ops\' Operations Metrics\Investigation Documentation\GIACT Investigations\SDS_Cases\_" & dte & ".xlsx", FileFormat:=51
NewWb.Close SaveChanges:=False
Else
MsgBox "This is not a date. Please try again"
End If
End Sub

Setting excel VBA Range from multiple variables

I'm having trouble with the Range function. (Nearly) completed code below. I'm fairly new to VBA, so please explain the basics if you have the time. This is the line that is giving me a debug error:
Set CombinedPropRange = ThisWorkbook.Worksheets("PropFiltered").Range("A" & _
PropACount & ":J" & SplitTabName(2))
Full Code Below:
Sub FillTabsTest()
' FillTabsTest Macro
HowManyTabsDoYouNeed = 4 'If you want to add or remove Tabs, you must change this number AND add/subtract from the "TabName(1)" section below.
ReDim TabName(1 To HowManyTabsDoYouNeed) As String
'Grabs Data from Original Workbook and creates a new Workbook.
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range("A1:P1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Call WrapText
TabName(1) = "April H.,0,1000"
TabName(2) = "Christopher H.,0,1000"
TabName(3) = "Christie E.,500,500"
TabName(4) = "Cori M.,500,500"
'Places Filtered Auto Events on its own tab
Sheets("Sheet1").Select
Cells.Select
Selection.AutoFilter
ActiveSheet.Range("$A:$S").AutoFilter Field:=8, Criteria1:="=COMAUTO", _
Operator:=xlOr, Criteria2:="=PERSAUTO"
ActiveSheet.Range("$A:$S").AutoFilter Field:=5, Criteria1:="=3*", Operator _
:=xlAnd
ActiveSheet.Range("$A:$S").AutoFilter Field:=9, Criteria1:=Array( _
"AUTO BODILY INJURY", "AUTO MED PAY", "AUTO PROPERTY DAMAGE", "AUTO-ENDORSEMENT", _
"AUTO-OTHER", "BODILY INJURY", "COLLISION", "COMPREHENSIVE", "LIABILITY", "OTHER", _
"RENTAL REIMBURSEMENT", "UM/UIM"), Operator:=xlFilterValues
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "AutoFiltered"
ActiveSheet.Paste
'Places Filtered Property Events on its own tab
Sheets("Sheet1").Select
Cells.Select
Application.CutCopyMode = False
ActiveSheet.ShowAllData
Cells.Select
ActiveSheet.Range("$A:$S").AutoFilter Field:=8, Criteria1:="=COMPROP", _
Operator:=xlOr, Criteria2:="=PLPROP"
ActiveSheet.Range("$A:$S").AutoFilter Field:=5, Criteria1:="=3*", Operator _
:=xlAnd
ActiveSheet.Range("$A:$S").AutoFilter Field:=12, Criteria1:="<>*FIRE*", _
Operator:=xlOr, Criteria2:="<>*SMOKE*"
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "PropFiltered"
ActiveSheet.Paste
'Begin adding the above named tabs to the workbook
For i = 1 To HowManyTabsDoYouNeed
Sheets.Add After:=Sheets(Sheets.Count)
SplitTabName = Split(TabName(i), ",")
ActiveSheet.Name = SplitTabName(0)
Next i
'Begin populating employee's sheets.
Dim AutoACount As Integer
Dim PropACount As Integer
' Dim AutoAPasteCount As Integer
Dim PropAPasteCount As Integer
Dim AutoJCount As Integer
Dim PropJCount As Integer
'Dim AutoRangeA As Range
'Dim AutoRangeJ As Range
'Dim PropRangeA As Range
'Dim PropRangeJ As Range
Dim PropAPasteCountRange As String
Dim CombinedPropRange As Range
Dim CombinedAutoRange As Range
AutoACount = 2
PropACount = 2
AutoJCount = 2
PropJCount = 2
PropAPasteCount = 2
For i = 1 To HowManyTabsDoYouNeed
SplitTabName = Split(TabName(i), ",")
If SplitTabName(1) <> "0" Then
' Set AutoRangeA = Range("A" & AutoACount)
' Set AutoRangeJ = Range("J" & SplitTabName(1))
Sheets("AutoFiltered").Select
Set CombinedAutoRange = ThisWorkbook.Worksheets("AutoFiltered").Range("A" & AutoACount & ":J" & SplitTabName(1))
CombinedAutoRange.Copy
Sheets("SplitTabName(0)").Select
ActiveSheet.Paste
AutoACount = AutoACount + SplitTabName(1)
PropAPasteCount = SplitTabName(1)
End If
If SplitTabName(2) <> "0" Then
'Set PropRangeA = Range("A" & PropACount)
'MsgBox PropRangeA
'Set PropRangeJ = Range("J" & SplitTabName(2))
PropAPasteCountRange = "A" & PropAPasteCount
'Sheets("PropFiltered").Select
Set CombinedPropRange = ThisWorkbook.Worksheets ("PropFiltered").Range("A" & PropACount & ":J" & SplitTabName(2))
CombinedPropRange.Copy
Sheets("SplitTabName(0)").Select
ThisWorkbook.Worksheets(SplitTabName(0)).Cells(PropAPasteCountRange).Select
ActiveSheet.Paste
PropACount = PropACount + SplitTabName(2)
End If
Next i
End

VBA macro to group all rows under one heading, headings when more than one heading exists

I am writing a vba macro to achieve the following but do not how to implement it. Would any please provide some guidance?
Currently, the data is as follows(subitem spans from column B onwards):
ITEM ONE [Subitem one... ]
ITEM ONE [Subitem two ...]
ITEM ONE [Subitem three...]
ITEM TWO [Subitem one ...]
ITEM THREE [Subitem one...]
ITEM Three [Subitem two...]
The following is what the data should look like in a separate sheet:
ITEM ONE
--------
Subitem one
Subitem two
Subitem three
ITEM TWO
--------
Subitem one
ITEM THREE
----------
Subitem one
Subitem two
Any guidance/help will be greatly appreciated.
Edited: solution as follows:
r = Range("a65536").End(xlUp).Row
c = Range("IU1").End(xlToLeft).Column
a = Split(Cells(, c).Address, "$")(1)
MsgBox "last row with data is " & r & " and last column with data is " & a & "", vbOKOnly, "LastRow and LastCol"
rr = r + 1
Application.Visible = False
Range("A1:" & a & r & "").Sort Key1:=Range("B2"), Order1:=xlAscending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
Sheets("owssvr(1)").Select
Sheets.Add
'by default select first record and paste in reports sheet
Sheets("owssvr(1)").Select
Range("b2").Select
Selection.Copy
Sheets(1).Select
Range("b2").Select
ActiveSheet.Paste
'paste header below it
Sheets("owssvr(1)").Select
Range("c1:" & a & "2").Select
Selection.Copy
Sheets(1).Select
Range("b3").Select
ActiveSheet.Paste
For i = 3 To r
Sheets(2).Select
'Program name is same as above, dont copy name but row starting from next col, switch to other sheet, find last row in col B, add one to last row and paste
If Cells(i, 2).Value = Cells(i - 1, 2) Then
Range("C" & i & ":" & a & i & "").Select
Selection.Copy
Sheets(1).Select
'Range("b3").Select
lr2 = Range("b65536").End(xlUp).Row
Range("B" & lr2 + 1 & "").Select
ActiveSheet.Paste
Else
'if name is not same as above, copy name, find last row, add two to add a gap from prev program name, paste program name, move to next row and paste remaining cols
Sheets(2).Select
Range("B" & i & "").Select
Selection.Copy
Sheets(1).Select
lr2 = Range("b65536").End(xlUp).Row
Range("B" & lr2 + 2 & "").Select
ActiveSheet.Paste
'copy headers
Sheets(2).Select
Range("c1:" & a & "1").Select
Selection.Copy
Sheets(1).Select
lr2 = Range("b65536").End(xlUp).Row
Range("B" & lr2 + 1 & "").Select
ActiveSheet.Paste
'copy cells(row, col+1)
Sheets(2).Select
Range("C" & i & ":" & a & i & "").Select
Selection.Copy
Sheets(1).Select
'Range("b3").Select
lr2 = Range("b65536").End(xlUp).Row
Range("B" & lr2 + 1 & "").Select
ActiveSheet.Paste
End If
Next
What you're asking for can be done with a PivotTable. I'm working in Excel 2010, but 2003 should probably have the same functionality. This is how it would look like.
The naive VBA approach I was going to do (which I guess you've implemented) was looping through all the items, doing comparisons, and adding them one at a time to the new worksheet. This can be made a bit more efficient if you store the initial range (of 2 columns) in an array, loop through that and store the output in a 2nd array, then copy the array back to a range.
I'm not sure how much data you have or how long that operation takes. Another alternative would be to use the macro recorder to make a PivotTable and copy the data from there to a new sheet. Here's an example, though you'd want to change the worksheet and range references to make them explicit/dynamic. The example data range is A1:B9.
Sub Example()
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet1!R1C1:R9C2", Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:="Sheet4!R3C1", TableName:="PivotTable1", DefaultVersion _
:=xlPivotTableVersion14
Sheets("Sheet4").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("item1")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("sub12")
.Orientation = xlRowField
.Position = 2
End With
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Sheet2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
your old worksheet is called yourWorksheet.
create a new worksheet:
set newWS = thisworkbook.workbooks.add()
dim rr as long
rr =1
for r = startRow to yourWorksheet.UsedRange.Rows.Count
firstItem = yourWorksheet.cells(r,1).value
newWS.cells(rr,1).value = firstItem
rr = rr + 1
do while firstItem = yourworksheet.cells(r,1).value
newWS.cells(rr,1).value = yourworksheet.cells(rr,2).value 'copy all columns here
rr = rr + 1
r =r + 1
loop
next r
rough and untested, but that's the idea.
If you use the left command and extract the Item One, Item Two, etc.
Heading(row) = Left(Cells(row,"B"), 8)
then extract the subItem:
SubItem(row) = Left(Right(cells(row, "B"), 20), 10)
These will extract the text.
You have to get creative for THREE and FOUR.
Sub Sort1()
'
' Sort1 Macro
' Macro recorded 7/30/2012 by American International Group
'
'
Dim r As Integer
Dim c As Integer
Dim lr2 As Integer
Dim a As String
Dim b As String
Dim cdb As Long
Dim name1 As String
Dim name2 As String
n1 = InputBox(Prompt:="Enter a name for worksheet else click OK", Title:="Enter a name for this sheet", Default:="owssvr")
n2 = InputBox(Prompt:="Enter a name for the Report view sheet else click OK", Title:="Enter a name for Report sheet", Default:="reportView")
b = InputBox(Prompt:="Enter Column Name on which to sort data", Title:="Sort by", Default:="B")
b = UCase(b) 'convert to uppercase e.g.c to C
asciiCol = Asc(b) 'convert to ascii 66
asciiNext = asciiCol + 1 'add one to ascii to get next column ascii code e.g. 66+1=67 to get D
sortbyColNo = 0
sortbyColNo = Range(b & "1").Column
'Rename sheets to avoid conflict
Sheets(1).name = n1
Sheets("" & n1 & "").Select
r = Range("a65536").End(xlUp).Row
c = Range("IU1").End(xlToLeft).Column
a = Split(Cells(, c).Address, "$")(1)
x = Split(Cells(, c).Address, "$")(2)
MsgBox "last row with data is " & r & " and last column with data is " & a & "", vbOKOnly, "LastRow and LastCol"
rr = r + 1
'Application.Visible = False
Range("A1:" & a & r & "").Sort Key1:=Range("" & b & "2"), Order1:=xlAscending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
Sheets("" & n1 & "").Select
Sheets.Add
ActiveSheet.name = n2
'by default select first record and paste in reports sheet
Sheets("" & n1 & "").Select
Range("" & b & "2").Select
Selection.Copy
Sheets("" & n2 & "").Select
Range("b2").Select
ActiveSheet.Paste
'paste header below it
Sheets("" & n1 & "").Select
Range("" & Chr(asciiNext) & "1:" & a & "1").Select
With Selection
.Font.Bold = True
End With
Range("" & Chr(asciiNext) & "1:" & a & "2").Select
Selection.Copy
Sheets("" & n2 & "").Select
Range("b3").Select
ActiveSheet.Paste
'start from row 3
For i = 3 To r
Sheets("" & n1 & "").Select
'Program name is same as above, dont copy name but row starting from next col, switch to other sheet, find last row in col B, add one to last row and paste
If Cells(i, sortbyColNo).Value = Cells(i - 1, sortbyColNo) Then
Range("" & Chr(asciiNext) & "" & i & ":" & a & i & "").Select
Selection.Copy
Sheets("" & n2 & "").Select
'Range("b3").Select
lr2 = Range("b65536").End(xlUp).Row
Range("B" & lr2 + 1 & "").Select
ActiveSheet.Paste
Else
'if name is not same as above, copy name, find last row, add two to add a gap from prev program name, paste program name, move to next row and paste remaining cols
Sheets("" & n1 & "").Select
Range("" & b & "" & i & "").Select
Selection.Copy
Sheets("" & n2 & "").Select
lr2 = Range("b65536").End(xlUp).Row
Range("B" & lr2 + 2 & "").Select
ActiveSheet.Paste
'copy headers
Sheets("" & n1 & "").Select
Range("" & Chr(asciiNext) & "1:" & a & "1").Select
Selection.Copy
Sheets("" & n2 & "").Select
lr2 = Range("b65536").End(xlUp).Row
Range("B" & lr2 + 1 & "").Select
ActiveSheet.Paste
'copy cells(row, col+1)
Sheets("" & n1 & "").Select
Range("" & Chr(asciiNext) & i & ":" & a & i & "").Select
Selection.Copy
Sheets("" & n2 & "").Select
'Range("b3").Select
lr2 = Range("b65536").End(xlUp).Row
Range("B" & lr2 + 1 & "").Select
ActiveSheet.Paste
End If
Next
'Application.Visible = True
'formatSheet
End Sub

Resources