I have this macro to delete the entire rows for those that are not "chr9". I have a total of 401,094 rows. It seems to compile fine, but my Excel freezes and I have to Force Quit.
I think it may be an inefficient algorithm or maybe some error in the code?
Sub deleteNonChr9()
Dim lastrow As Long
Dim firstrow As Long
Dim i As Long
lastrow = 401094
firstrow = 0
' Increment bottom of sheet to upwards
For i = lastrow To firstrow Step -1
If (Range("C1").Offset(i, 0) <> "chr9") Then
Range("C1").Offset(i, 0).EntireRow.Delete
End If
Next i
End Sub
The fastest way to conditionally delete rows is to have them all at the bottom of the data block. Sorting them into that position and deleting is faster than individual looping or even compiling a discontiguous Union of rows to delete.
When any group or cells is contiguous (i.e. all together) Excel does not have to work as hard to get rid of them. If they are at the bottom of the Worksheet.UsedRange property, Excel doesn't have to calculate what to fill the empty space with.
Your original code did not allow for a column header text label in row 1 but I will account for that. Modify to suit if you do not have one.
These will turn off the three primary parasites of computing power. Two have already been addressed in the comments and answers, the third Application.EnableEvents property can also make a valid contribution to Sub procedure efficiency whether you have event driven routines or not. See the helper Sub procedure at the bottom for details.
Sample data²: 500K rows of random data in A:Z. ~33% Chr9 in column C:C. Approximately 333K randomly discontiguous rows to delete.
Union and delete
Option Explicit
Sub deleteByUnion()
Dim rw As Long, dels As Range
On Error GoTo bm_Safe_Exit
appTGGL bTGGL:=False 'disable parasitic environment
With Worksheets("Sheet1")
Set dels = .Cells(.Rows.Count, "C").End(xlUp).Offset(1)
For rw = .Cells(.Rows.Count, "C").End(xlUp).Row To 2 Step -1
If LCase$(.Cells(rw, "C").Value2) <> "chr9" Then
Set dels = Union(dels, .Cells(rw, "C"))
End If
Next rw
If Not dels Is Nothing Then
dels.EntireRow.Delete
End If
End With
bm_Safe_Exit:
appTGGL
End Sub
Elapsed time: <It has been 20 minutes... I'll update this when it finishes...>
Bulk load from worksheet to variant array, change, load back, sort and delete
Sub deleteByArrayAndSort()
Dim v As Long, vals As Variant
On Error GoTo bm_Safe_Exit
appTGGL bTGGL:=False 'disable parasitic environment
With Worksheets("Sheet1")
With .Cells(1, 1).CurrentRegion
.EntireRow.Hidden = False
With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
'bulk load column C values
vals = .Columns(3).Value2
'change non-Chr9 values into vbNullStrings
For v = LBound(vals, 1) To UBound(vals, 1)
If LCase$(vals(v, 1)) <> "chr9" Then _
vals(v, 1) = vbNullString
Next v
End With
'dump revised array back into column C
.Cells(2, "C").Resize(UBound(vals, 1), UBound(vals, 2)) = vals
'sort all of blank C's to the bottom
.Cells.Sort Key1:=.Columns(3), Order1:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlYes
'delete non-Chr9 contiguous rows at bottom of currentregion
.Range(.Cells(.Rows.Count, "C").End(xlUp), .Cells(.Rows.Count, "C")).EntireRow.Delete
End With
.UsedRange 'reset the last_cell property
End With
bm_Safe_Exit:
appTGGL
End Sub
Elapsed time: 11.61 seconds¹ (166,262 rows of data remaining²)
Original code
Elapsed time: <still waiting...>
Summary
There are obvious advantages to working within a variant array as well as deleting contiguous ranges. My sample data had ~66% of the rows to delete so it was a harsh task master. If there were 5 or 20 rows to delete, using an array to parse data for a sort may not be the best solution. You will have to make your own decisions based on your own data.
appTGGL helper Sub procedure
Public Sub appTGGL(Optional bTGGL As Boolean = True)
With Application
.ScreenUpdating = bTGGL
.EnableEvents = bTGGL
.Calculation = IIf(bTGGL, xlCalculationAutomatic, xlCalculationManual)
End With
Debug.Print Timer
End Sub
¹ Environment: old business class laptop with a mobile i5 and 8gbs of DRAM running WIN7 and Office 2013 (version 15.0.4805.1001 MSO 15.0.4815.1000 32-bit) - typical of the low end of the scale for performing this level of procedure.
² Sample data temporarily available at Deleting entire row cannot handle 400,000 rows.xlsb.
Toggling ScreenUpdating and Calculation will help. But as Jeeped stated, applying a custom sort order is the way to go.
Sub deleteNonChr9()
Dim lastrow As Long
Dim firstrow As Long
Dim i As Long
lastrow = 401094
firstrow = 1
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' Increment bottom of sheet to upwards
For i = lastrow To firstrow Step -1
If (Cells(i, "C") <> "chr9") Then
Rows(i).EntireRow.Delete
End If
Next i
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
Major Progress
The following code for dealing with deleting a very large number of rows is inspired by Ron de Bruin - Excel Automation.
Sub QuickDeleteRows()
Dim Sheet_Data As Worksheet, NewSheet_Data As Worksheet
Dim Sheet_Name As String, ZeroTime As Double, Data As Range
On Error GoTo Error_Handler
SpeedUp True
Set Sheet_Data = Sheets("Test")
Sheet_Name = Sheet_Data.Name
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
Set Data = Sheet_Data.Range("A1", Cells(LastRow, LastColumn))
Set NewSheet_Data = Sheets.Add(After:=Sheet_Data)
Data.AutoFilter Field:=3, Criteria1:="=Chr9"
Data.Copy
With NewSheet_Data.Cells
.PasteSpecial xlPasteColumnWidths
.PasteSpecial xlPasteAll
.Cells(1, 1).Select
.Cells(1, 1).Copy
End With
Sheet_Data.Delete
NewSheet_Data.Name = Sheet_Name
Safe_Exit:
SpeedUp False
Exit Sub
Error_Handler:
Resume Safe_Exit
End Sub
Sub SpeedUp(SpeedUpOn As Boolean)
With Application
If SpeedUpOn Then
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
.DisplayStatusBar = False
.DisplayAlerts = False
Else
.ScreenUpdating = True
.EnableEvents = True
.Calculation = xlCalculationAutomatic
.DisplayStatusBar = True
.DisplayAlerts = True
End If
End With
End Sub
While my old version of code takes time rather long (about 130 seconds on average) for handling sample data provided by Jeeped, but the code above completes less than 4.6 seconds for handling 400,000 rows of sample data on my machine. It's a very significant gain in performance!
System Information of my PC (Very Minimum Computer Configurations for Students)
Operating System: Windows 7 Professional 32-bit (6.1, Build 7601)
Service Pack 1
System Manufacturer: Hewlett-Packard
System Model: HP Pro 3330 MT
Processor: Intel(R) Core(TM) i3-2120 CPU # 3.30GHz (4
CPUs), ~3.3GHz
Memory: 2048MB RAM
Original Answer
I'm aware that this answer is not really what the OP wants, but maybe this answer can be useful for other users and helpful to future users, if not the OP. Please see this answer as the alternative method.
Copy/paste, cut/insert, and delete entire row operations in Excel can take an excessively long time even when doing it in VBA Excel. For copy/paste and cut/insert operations the cause of the slowness is the formatting of the data itself. Memory over-allocation is another cause of those operations. So how do we resolve a situation like this? There are several things you can look for speeding up your code.
Use arrays instead of the range of cells. It's usually considered to be faster than working on the range of cells because it ignores the formatting of the data in cells.
Use .Value2 rather than the default property (.Value) because .Value2 will only treat all formatting numbers (currency, accounting, date, scientific, etc) as Doubles.
Suppose we have 10,000 rows of dummy data like the following dataset:
Instead of deleting entire rows of "non-chr9" data, I simply ignore those data and only consider the "chr9" data by copying all the "chr9" data into an array. How to code to implement such task? First of all, we must make a copy of our data to avoid data loss because we cannot undo all changes to recover the original data after running VBA Excel.
It seems you have done all the preparations needed. Now, we may start coding by first declaring every variable we need to the appropriate type of data.
Dim i As Long, j As Long, k As Long
Dim LastRow As Long, LastColumn As Long, LengthDataChr9 As Long
If you don't declare the variables, your code will run with those variables defaulting to the Variant type. While Variant can be enormously useful, but it can make your code slow. So, make sure each variable is declared with a sensible type. This is good programming practice and considerably faster.
Next, we determine all variables we will use to construct the size of arrays. We will need
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
LastRow and LastColumn are the row and column number of the last cell with data in one row or one column. Keep in mind, LastRow and LastColumn may not give you the desired row and column number if you are not setting them up properly or using a well-formatted data sheet. What I mean by a "well-formatted data sheet", is a worksheet with data that starts in cell A1 and the number of the rows in column A and columns in row 1 must be equal to the range of all data. In other words, the size of the range of all data must be equal to LastRowxLastColumn.
We also need the length of the array for storing all the "chr9" data. This can be done by counting all the "chr9" data using the following statement:
LengthDataChr9 = Application.CountIf(Columns("C"), "chr9")
We now know the size of the arrays and we can redimension it. Add the following code lines:
ReDim Data(1 To LastRow, 1 To LastColumn)
ReDim DataChr9(1 To LengthDataChr9, 1 To LastColumn)
We use ReDim instead of Dim because we use the dynamic arrays. VBA Excel has automatically declared the arrays defaulting to the Variant type, but they have no size yet. Next, we copy the data into the array Data by using statement
Data = Range("A1", Cells(LastRow, LastColumn)).Value2
We use .Value2 to improve the performance of the code (See speeding up tips point 2 above). Since the data has already copied to the array Data we may clear the worksheet data so we can use it to paste DataChr9.
Rows("1:" & Rows.Count).ClearContents
To clear everything (all contents, formats, etc.) on the worksheet, we may use Sheets("Sheet1").Cells.Clear or Sheet1.Cells.Clear. Next, we want the code to loop through the elements array Data in column 3 by using For ... Next statement because the desired data we're looking for are located there. If the element of array Data contains string "chr9" is found, the code then copying all the elements in the row where "chr9" is located into DataChr9. Again we use For ... Next statement. Here are the lines for implementing those procedures.
For i = 1 To UBound(Data)
If Data(i, 3) = "chr9" Then
j = j + 1
For k = 1 To LastColumn
DataChr9(j, k) = Data(i, k)
Next k
End If
Next i
where j = j + 1 is a counter for looping through the rows of DataChr9. The final step, we paste back all the elements of DataChr9 to the worksheet by adding this line to the code:
Range("A1", Cells(LengthDataChr9, LastColumn)) = DataChr9
and then you're done! Yay, finally!
OK, let's compile all the lines code above. We obtain
Sub DeleteNonChr9()
Dim i As Long, j As Long, k As Long
Dim LastRow As Long, LastColumn As Long, LengthDataChr9 As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
LengthDataChr9 = Application.CountIf(Columns("C"), "chr9")
ReDim Data(1 To LastRow, 1 To LastColumn)
ReDim DataChr9(1 To LengthDataChr9, 1 To LastColumn)
Data = Range("A1", Cells(LastRow, LastColumn)).Value2
Rows("1:" & Rows.Count).ClearContents
For i = 1 To UBound(Data)
If Data(i, 3) = "chr9" Then
j = j + 1
For k = 1 To LastColumn
DataChr9(j, k) = Data(i, k)
Next k
End If
Next i
Range("A1", Cells(LengthDataChr9, LastColumn)) = DataChr9
End Sub
The performance of the code above is satisfying. It takes less than 0.5 seconds on average to complete the process of extracting all "chr9" data from 10,000 rows dummy data on my machine.
Related
I am attempting to edit my code because although it functions as needed, I know it is not efficient. I am copying 5 merged cells at a time and pasting copied data in the column to the left before clearing the copied range.
Every 6th cell is skipped because it does not apply to what needs to be moved. A snippet is below, I know there is a much more efficient way to do what I am doing here, but I am brand new and have basically no experience in declaring variables or utilizing loops, functions, etc.
Thanks in advance!
Option Explicit
Sub ShiftWeeks()
Dim answer As VbMsgBoxResult
answer = MsgBox("Are you sure you want to copy/paste this weeks data?", vbYesNo, "Press Button for Macro")
If answer = vbYes Then
Range("c3:c8").Copy
Range("b3:b8").PasteSpecial xlPasteValues
Range("c3:c8").ClearContents
Range("c10:c15").Copy
Range("b10:b15").PasteSpecial xlPasteValues
Range("c10:c15").ClearContents
Range("c17:c22").Copy
Range("b17:b22").PasteSpecial xlPasteValues
Range("c17:c22").ClearContents
Range("c24:c29").Copy
Range("b24:b29").PasteSpecial xlPasteValues
Range("c24:c29").ClearContents
End If
End Sub
I've copied the same 3 code blocks quite a few times and have just changed the range. The button I made works, but I know the code is junk and it's not that difficult, but I don't know how to clean it up.
Not to nit-pick but it looks like you're actually copying 6 rows at a time, not 5 (e.g. C3:C8 is six rows). Following the same pattern you have above, you could use a For x = y to z step a -style loop, like below. If the last row will always be the same, you could define it with a lastRow = y statement, otherwise you can determine it dynamically with something like lastRow = ws.Cells(ws.Rows.Count, 3).End(xlUp).Row.
For x = 3 To lastRow Step 7
ws.Range(ws.Cells(x, 3), ws.Cells(x + 5, 3)).Copy
ws.Range(ws.Cells(x, 2), ws.Cells(x + 5, 2)).PasteSpecial xlPasteValues
ws.Range(ws.Cells(x, 3), ws.Cells(x + 5, 3)).ClearContents
Next x
Looping
If you need to add a dozen more ranges, having to repeat lines of code per range is tedious and will quickly become unmanageable. To avoid this issue, you can change the code into a loop.
There are two ways to create the loop.
By blocks:
Sub Example()
For r = 3 To 24 Step 7
With Cells(r, 3).Resize(6)
.Offset(0, -1).Value = .Value
.ClearContents
End With
Next
End Sub
And by cells:
Sub Example()
Dim Cell As Range
For Each Cell In Range("c3:c8,c10:c15,c17:c22,c24:c29")
With Cell
.Offset(0, -1).Value = .Value
.ClearContents
End With
Next
End Sub
In the Block loop, we define the starting locations (r=3 and Cells ColumnIndex:=3) and then the block size (Step 7 and Resize(6)). In the Cells loop we simply define the range we want to operate within and execute the desired actions on every cell within that range.
In both methods, adding new locations to the macro would be as simple as changing the For loop statement line. Either by increasing the ending number from 24 or by adding more addresses to the Range.
Clipboard Copying
The clipboard is not a native feature of Excel and is actually a part of Windows. This means that when you use .Copy and .PasteSpecial in seperate lines, Excel has to communicate with windows and share the data. This is significantly slower than having the data stay within Excel. This issue is avoided by doing Range2.Value = Range1.Value and directly assigning the data without using the clipboard. You can also do Range1.Copy Destination:=Range2 but this will copy over the formatting as well as the values.
Additional Improvements
If you test out the cells loop, you'll notice that the application stutters and can be quite slow. To avoid this, you'll want to temporarily disable automatic actions by the application so that it doesn't pause during each loop. The application wants to re-calculate the sheet after every change and refresh the screen to display new values. Both of these are the cause of the stuttering and disabling them during the macro will speed things up significantly.
Sub Example()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
''''''''''''''''
'Code goes here'
''''''''''''''''
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
Copy Merged Ranges
Option Explicit
Sub ShiftWeeks()
Const wsName As String = "Sheet1"
Const fRow As Long = 3
Const sCol As String = "C"
Const cOffset As Long = -1
Const rOffset As Long = 7 ' needed only for the second solution
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
Dim answer As VbMsgBoxResult
answer = MsgBox("Are you sure you want to copy/paste this weeks data?", vbYesNo, "Press Button for Macro")
If answer = vbYes Then
Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, sCol).End(xlUp).Row
If lRow < fRow Then Exit Sub ' no data
' 1.) If the rows between the merged ranges are empty...
Dim srg As Range: Set srg = ws.Cells(fRow, sCol).Resize(lRow - fRow + 1)
srg.Offset(, cOffset).Value = srg.Value
srg.Value = Empty
' 2.) ... otherwise:
' Dim sCell As Range
' Dim r As Long
'
' For r = fRow To lRow Step rOffset
' Set sCell = ws.Cells(r, sCol)
' sCell.Offset(, cOffset).Value = sCell.Value
' sCell.Value = Empty
' 'sCell.MergeArea.ClearContents
' Next r
End If
End Sub
I have been given a work task where im to find and replace 8 digits numbers with a corresponding new values coming from a 2 column table....basically a vlookup then replace the old value with a new one...
The challenge im facing is.... the 2 column table is 882k rows, and the cells im trying to replace is about 120 million (41,000 rows x 3000 columns)...
I tried running a vba code i found somewhere...
Option Explicit
Sub Replace_Overwrite()
Dim LRow As Long, i As Long
Dim varSearch As Variant
With Sheets("Sheet2")
LRow = .Cells(.Rows.Count, 1).End(xlUp).Row
varSearch = .Range("A2:B" & LRow)
End With
With Sheets("Sheet1").UsedRange
For i = LBound(varSearch) To UBound(varSearch)
.Replace what:=varSearch(i, 1), replacement:=varSearch(i, 2), lookat:=xlWhole
Next
End With
End Sub
I tried using this and it ran it for 8 hours and my work laptop crashed....
I'm not sure anymore if this is still possible with MS Excel alone...
I wonder if anyone can help me with a code that can process it.. i can leave my system open over the weekend if its stable and does work.. it only has 8GB ram btw, running excel 2013...
To speed up things, do as much as possible in memory and minimize the interaction between VBA and Excel (as this makes things really slow).
The following attempt reads the lookup-list into a dictionary and then processes the data column by column.
I did a test, creating 880.000 lookup rows and 40.000 x 100 cells of data. Building the dictionary took less than a minute, processing the columns took 3-4 seconds per column. I added a logic that after every 10 columns, the whole workbook is saved, that increased the processing time but ensures that after a crash you can more or less continue where you left (the yellow color tells you where, just replace the 1 in for col=1 with the column where you want to restart).
I have added some DoEvents, that in theory slows down the process a little bit. Advantage is that you can see the output of the debug.print and the whole Excel process is not displayed as unresponsive in the task manager.
To build the dictionary, I read the complete data into an array at once (if you are not familiar with Dictionaries: You need to add a reference to the Microsoft Scripting Runtime).
Function createDict() As Dictionary
Dim d As New Dictionary
Dim rowCount As Long
Dim list()
Debug.Print Now, "Read data from Lookup sheet"
With ThisWorkbook.Sheets(1)
rowCount = .Cells(.Rows.Count, 1).End(xlUp).row
list = .Range("A1:B" & rowCount).Value
End With
Debug.Print Now, "Build dictionary."
Dim row As Long
For row = 1 To UBound(list)
If Not d.Exists(list(row, 1)) Then d.Add list(row, 1), list(row, 2)
If row Mod 1000 = 0 Then DoEvents
Next row
Set createDict = d
End Function
As said, replacing the data is done column by column. Again, I read the whole column at once into an array, do the replace on this array and then write it back to the sheet.
Sub replaceAll()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim d As Dictionary
Set d = createDict
Dim row As Long, col As Long
Dim rowCount As Long, colCount As Long
With ThisWorkbook.Sheets(2)
rowCount = .Cells(.Rows.Count, 1).End(xlUp).row
colCount = .Cells(1, .Columns.Count).End(xlToLeft).Column
For col = 1 To colCount
Debug.Print Now & "processing col " & col
DoEvents
Dim data
data = .Range(.Cells(1, col), .Cells(rowCount, col))
For row = 1 To rowCount
If d.Exists(data(row, 1)) Then data(row, 1) = d(data(row, 1))
Next row
.Range(.Cells(1, col), .Cells(rowCount, col)) = data
.Cells(1, col).Interior.Color = vbYellow
If col Mod 10 = 0 Then ThisWorkbook.Save
Next
End With
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
One remark: You should consider to use a database for such amount of data.
I have VBA running on an Excel sheet that translates the data in the sheet so I can import it into another application.
The below function cleans the data and removes text wrapping. This function takes a long time to run when the sheets have a large cell count. Since I am normalizing data to import to a relational database, there are frequently a lot of cells across the seven different sheets I have.
Is there a more efficient way to remove the text wrap and clean the data in the cells?
Dim ws As Worksheet
Dim x, lrow, lcol, active As Long
Dim r, cel As Range
active = ActiveWorkbook.Worksheets.count
For x = 1 To active
Set ws = ThisWorkbook.Sheets(x)
ws.Select
Select Case ws.name
Case "Solution", "Description", "Problem", "Buyer", "ProjectType", "Process", "Feature"
lrow = ws.UsedRange.Rows(ActiveSheet.UsedRange.Rows.count).row
lcol = ws.UsedRange.Columns(ActiveSheet.UsedRange.Rows.count).Column
If lrow > 1 Then
Set r = ws.Range(Cells(2, 1), Cells(lrow, lcol))
For Each cel In r.Cells
cel.WrapText = False
cel.Value = Application.WorksheetFunction.Clean(cel.Value)
Next cel
End If
Case Else
End Select
ws.Cells(1, 1).Select
ThisWorkbook.Sheets("Solution").Activate
Next x
Your code can be reduced to
Sub Demo()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Select Case ws.Name
Case "Solution", "Description", "Problem", "Buyer", "ProjectType", "Process", "Feature"
With ws.UsedRange
.WrapText = False
.Value = ws.Evaluate("Clean(" & .Address & ")")
End With
End Select
Next
End Sub
On my hardware, a sheet with 100,000 rows 26 columns ran in about 6s
Note: OPs claim (in comment) that "it changes the value of every cell on the sheet to the first value in the first sheet it encounters." - tested this claim and it's not accurate. This code works as advertised.
To remove the text wrapping property (and it surprises me that has an affect on your external program), you should be able to do just:
r.WrapText = False
For the Clean, what, exactly, is in the cells that you are trying to remove?
It would be faster to read the cells into an array; process them, and write them back.
Something like: (not debugged)
Dim V, I as long, J as Long
v = R
for i = 1 to ubound(v)
for j = 1 to ubound(v,2)
`worksheetfunction.clean(v(i,j))
`or some other function to remove unwanted characters
next j
next i
r.clear
r.value = v
You should also be aware that UsedRange is not particularly reliable and may wind up with you processing many more cells than necessary.
There are a number of posts on this forum showing better methods of determing the Last Row and Last Column.
In the code attached (two macros) if I call "SortBy Ecode" from within "EcodeKeep" the code never ends. (or at least doesn't end within 5 min when I force Quit excel).
However, If I run "SortByEcode" seperately before running "EcodeKeep" they each run in under 2 seconds.
There are a little over 19K rows of data in the spreadsheet. Also, this is my first attempt at working with arrays in VBA.
What am I doing wrong?
Sub EcodeKeep()
Dim i As Long
Dim LastRow As Long
Call SortByEcode 'Calling this sort macro here causes this code to run forever.
Dim wks As Worksheet
Set wks = rawData5 'Work in sheet("RawEquipHistory")
LastRow = wks.Range("A" & Rows.Count).End(xlUp).Row
StartTime = Timer
Dim Ecode_arr() As Variant
ReDim Ecode_arr(LastRow)
Dim Results_arr() As String
ReDim Results_arr(LastRow)
For i = 0 To LastRow - 1 'Read data into Ecode_arr(i)
Ecode_arr(i) = wks.Range("A" & i + 1)
Next i
wks.Range("AM1") = "ECODE KEEP" 'Add the header to "S1"
For i = 0 To LastRow - 1
If Ecode_arr(i + 1) <> Ecode_arr(i) Then
Results_arr(i) = True
Else
Results_arr(i) = False
End If
wks.Range("AM" & i + 2) = Results_arr(i)
Next i
End Sub
Sub SortByEcode()
' SORT sheet by E-Code (Column A)
Dim LastRow As Long
LastRow = ThisWorkbook.Sheets("RawEquipHistory").Range("A" & Rows.Count).End(xlUp).Row
With ThisWorkbook.Sheets("RawEquipHistory").Sort ' SORT sheet by E-Code(a)
.SortFields.Clear
.SortFields.Add Key:=Range("A1:A" & LastRow), Order:=xlAscending
.SetRange Range("A1:AZ" & LastRow)
.Header = xlYes
.Apply
End With
End Sub
Your loop isn't infinite, only inefficient.
Unless you've disabled automatic calculations, application/worksheet events, and screen updating, then every time a cell is written to, Excel tries to keep up with the changes, and eventually fails to do so, goes "(not responding)", and at that point there's not much left to do but wait it out... and it can take a while.
You can work on the symptoms and disable automatic calculations, application/worksheet events, and screen updating - your code will run to completion, faster.
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Application.ScreenUpdating = False
Of course you would then reset these to their original values after the loops are completed, and you want to be careful to also reset them if anything goes wrong in the procedure, i.e. whenever you toggle those, you want an error-handling subroutine.
Or you can work on the root cause, and tweak the approach slightly, by reducing the worksheet operations to a bare minimum: one single read, one single write. ...and then whether automatic calculations are enabled, whether Excel fires worksheet events and repaints the screen every time you write to a cell will make no difference at all.
The secret sauce, is variant arrays. You had the right idea here:
Dim Ecode_arr() As Variant
ReDim Ecode_arr(LastRow)
Dim Results_arr() As String
ReDim Results_arr(LastRow)
But then reading the values one by one takes a toll:
For i = 0 To LastRow - 1 'Read data into Ecode_arr(i)
Ecode_arr(i) = wks.Range("A" & i + 1)
Next i
Don't bother sizing the arrays, keep them as plain old Variant wrappers - with Application.Transpose, you can get a one-dimensional Variant array from your one-column source range:
Dim ecodes As Variant
ecodes = Application.Transpose(wks.Range("A1:A" & LastRow).Value)
Now you can iterate this array to populate your output array - but don't write to the worksheet just yet: writing the values one by one to the worksheet is eliminating the need for a result/output array in the first place!
Note that because we are assigning a Boolean value with True in one branch and False in the other branch of a conditional, we can simplify the assignment by assigning directly to the Boolean expression of the conditional:
ReDim results(LBound(ecodes), UBound(ecodes))
Dim i As Long
For i = LBound(results) To UBound(results) - 1
results(i) = ecodes(i + 1) <> ecodes(i)
Next
And now that the results array is populated, we can dump it onto the worksheet, all at once - and since this is the only worksheet write we're doing, it doesn't matter that Excel wants to recalculate, raise events, and repaint: we're done!
wks.Range("AM2:AM" & i + 1).Value = results
Note: none of this is tested code, an off-by-one error might have slipped in as I adjusted the offsets (arrays received from Range.Value will always be 1-based). But you get the idea :)
I want make this basic function of "copy&paste-values-on-a-new-row-each-time" run as fast as possible since the macro repeats the calculations hundreds of thousands of times. I just can't find the exact answer after searching this forum for ages.
Currently, I'm copying output numbers from a fixed range and, elsewhere on the worksheet, pasting the values on a new row for each new set of results.
Here's the portion of the code doing this:
Row = Row +1
Range("g15:ax15").copy
Range("ea18").select
ActiveCell.Offset(Row,0).select
Selection.PasteSpecial Paste:=xlPasteValues
Now from what I have found on this forum, I can replace the Copy/Paste functions completely with Range(destination).value = Range(results).value to speed things up. However, I can't figure out how to do this if the destination rows need to be offset by 1 each time. Also, I've read that one could even do away with "select" to speed things up further! How?
There are a number of options:
//This uses the `Destination` key word
Sub CopyAndPaste()
Dim i as long
For i = 1 to 10
Range("g15:ax15").Copy Destination:=Range("ea18").Offset(i, 0)
next i
End Sub
//If you need `PasteSpecial` then you cannot use `Destination` hence this version
Sub CopyAndPaste()
Dim i as long
For i = 1 to 10
Range("g15:ax15").Copy
Range("ea18").Offset(i, 0).PasteSpecial Paste:=xlPasteValues
next i
End Sub
Sometimes reading values into an array first and then writing back to the spreadsheet is quicker. Here is an example:
Sub CopyAndPaste()
Dim i As Long, numbers As Variant, rw As Long
numbers = Range("g15:ax15")
rw = 18
For i = 1 To 10
rw = rw + 1
Range(Cells(rw, 131), Cells(rw, 131 + UBound(numbers, 2) - 1)) = numbers
Next i
End Sub
You can do it without copying as yo mention (using a variant array as you are copying values only, not formats)
X = Range("g15:ax15").Value2
[ea18].Offset(1, 0).Resize(UBound(X, 1), UBound(X, 2)).Value2 = X
or with your variable offset
Dim lngCnt As Long
lngCnt = lngCnt + 1
X = Range("g15:ax15").Value2
[ea18].Offset(lngCnt, 0).Resize(UBound(X, 1), UBound(X, 2)).Value2 = X
Row = Row +1
Range("g15:ax15").copy
Range("ea18").Offset(Row,0).PasteSpecial Paste:=xlPasteValues
Select is a more-or-less useless method inherited from recordings.