I have an excel range with 67 columns and about 4500 rows. The objective is to replace values in a row with hardcoded values in the 67th column of each row and then mark the ones that have have been replaced.
So I need to check each cell in a row (of 66 columns) and see if they satisfy a certain condition, before replacing them with the said hardcoded value at the very end of the row. My run time is about 360 seconds on average, when I mark the replaced values as Bold text.
Sub searchreplace()
Dim StartTime As Double
Dim Seconds As Double
StartTime = Timer
Dim i As Long
Dim j As Long
Dim arr As Variant
Dim myRange As Range
Dim Rng As String
Dim wb As Workbook
Dim SheetName As String
Dim LessThanEqual As Long
Application.ScreenUpdating = False
Set wb = ThisWorkbook
SheetName = "INPUT_WIND"
Rng = "C3:BQ4466"
LessThanEqual = 1
Set myRange = wb.Worksheets(SheetName).Range(Rng)
arr = myRange.Value
'i = rows = Ubound(arr,1)
'j=columns = Ubound(arr,2)
'loop through rows and clmns
For i = 1 To UBound(arr)
For j = 1 To myRange.Columns.Count
If arr(i, j) <= LessThanEqual Then
arr(i, j) = arr(i, 67)
myRange.Cells(i, j).Select
With Selection
.Font.Bold = True
End With
ElseIf IsEmpty(arr(i, j)) = True Then
arr(i, j) = arr(i, 67)
End If
Next j
Next i
myRange.Value = arr
Seconds = Round(Timer - StartTime, 2)
MsgBox "Fertig" & Seconds & "Seconds", vbInformation
Application.ScreenUpdating = True
End Sub
Instead of this:
myRange.Cells(i, j).Select
With Selection
.Font.Bold = True
End With
do this:
myRange.Cells(i, j).Font.Bold = True
It will be up to >10x faster.
See here for more: How to avoid using Select in Excel VBA
Here's a full example detailing using Union to keep track of which cells qualify to receive the bold, then apply that formatting in one shot. It's taking about a second on my machine to complete.
Option Explicit
Sub searchreplace()
Const LessThanEqual As Long = 1
Dim StartTime As Double
Dim i As Long
Dim j As Long
Dim arr As Variant
Dim myRange As Range
Dim wb As Workbook
Dim UnionRange As Range
StartTime = Timer
Application.ScreenUpdating = False
Set wb = ThisWorkbook
Set myRange = wb.Worksheets("INPUT_WIND").Range("C3:BQ4466")
arr = myRange.Value
For i = LBound(arr, 1) To UBound(arr, 1)
For j = LBound(arr, 2) To UBound(arr, 2)
If IsEmpty(arr(i, j)) = False And arr(i, j) <= LessThanEqual Then
If UnionRange Is Nothing Then
Set UnionRange = myRange.Cells(i, j)
Else
Set UnionRange = Union(UnionRange, myRange.Cells(i, j))
End If
ElseIf IsEmpty(arr(i, j)) Then
arr(i, j) = arr(i, 67)
End If
Next
Next
UnionRange.Font.Bold = True
myRange.Value = arr
Debug.Print "This took: " & Round(Timer - StartTime, 2) & " Seconds"
Application.ScreenUpdating = True
End Sub
Related
With following to this question Link
, I need to match the values found in wb1.coumns(1) with the other workbook wb2.coumns(1) with some particular conditions.
Wb2 will be filtered with the value Close at column 13 M.
My question: is to seek the Wb2 (the open workbook) Latest closing Date on column 11 K and then copy the respective values at columns (“B, and “Q:X”) (on the same row ),
Then paste these values in Wb1.columns (“S:AA”) respectively.
The below code designed to returns back with the respective values of only one column of wb2 (column “B”)
This is the Link for test workbooks.
Option Explicit
Option Compare Text
Sub Get_Respective_Values_Of_Last_Closing_Date()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim rng1 As Range, rng2 As Range
Dim arr1() As Variant, arr2() As Variant
Dim dict As New Dictionary
Application.ScreenUpdating = False
Set wb1 = ThisWorkbook
Set wb2 = Workbooks.Open(ThisWorkbook.path & "\Book_B.xlsb", UpdateLinks:=False, ReadOnly:=True)
Set ws1 = wb1.Sheets(1)
Set ws2 = wb2.Sheets(1)
Set rng1 = ws1.Range("A3:AA" & ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row) 'Main Range
Set rng2 = ws2.Range("A3:X" & ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row) 'Opened Workbook_Range
arr1 = rng1.Value2
arr2 = rng2.Value2
'place the unique last key in a dictionary:
Dim i As Long
For i = 1 To UBound(arr2)
If arr2(i, 13) = "Close" Then 'Column (Status)
If Not dict.Exists(arr2(i, 1)) Then
dict(arr2(i, 1)) = Array(arr2(i, 2), arr2(i, 11)) 'Place the _Date_ from K:K, too
Else
If CDate(arr2(i, 11)) > CDate(dict(arr2(i, 1))(1)) Then 'Change the item only in case of a more recent _Date_:
dict(arr2(i, 1)) = Array(arr2(i, 2), arr2(i, 11))
End If
End If
End If
Next i
'Place the necessary data in its place:
For i = 1 To UBound(arr1)
If dict.Exists(arr1(i, 1)) Then
arr1(i, 19) = dict(arr1(i, 1))(0) 'extract first item array element
Else
arr1(i, 19) = "NA"
End If
Next i
rng1.Value2 = arr1 'drop back the updated array content
ws1.Activate
' wb2.Close SaveChanges:=False
Application.ScreenUpdating = True
MsgBox "Ready..."
End Sub
Please, test the next updated code:
Sub Get_Respective_Values_Of_Last_Closing_Date()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim rng1 As Range, rng2 As Range
Dim arr1() As Variant, arr2() As Variant
Dim dict As New Dictionary
'Application.ScreenUpdating = False
Set wb1 = ThisWorkbook
Set wb2 = Workbooks.Open(ThisWorkbook.path & "\Book_B.xlsb", UpdateLinks:=False, ReadOnly:=True)
Set ws1 = wb1.Sheets(1)
Set ws2 = wb2.Sheets(1)
Set rng1 = ws1.Range("A3:AA" & ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row) 'Main Range
Set rng2 = ws2.Range("A3:X" & ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row) 'Opened Workbook_Range
arr1 = rng1.Value2
arr2 = rng2.Value2
'place the unique last key in a dictionary:
Dim i As Long, arrAtt, j As Long, k As Long
ReDim arrAtt(7) 'the 1D array should contain maximum number of elements from "Q" to "X"
'meaning 8 columns. since arrAtt is 1D zero based, it may keep 8 elements
For i = 1 To UBound(arr2)
If arr2(i, 13) = "Close" Then 'Column (Status)
Erase arrAtt: ReDim arrAtt(7) 'erase the previous loaded array, if the case (to be loaded...)
If Not dict.Exists(arr2(i, 1)) Then
For j = 0 To UBound(arrAtt) 'iterate between the 8 array elements
If arr2(i, 17 + j) <> "" Then
arrAtt(k) = arr2(i, 17 + k): k = k + 1 'add the found URLs and increment k
Else
Exit For 'exit the iteration if no URL exists
End If
Next j
If k > 0 Then ReDim Preserve arrAtt(k - 1) 'keep only the loaded elements
dict(arr2(i, 1)) = Array(arr2(i, 2), arr2(i, 11), arrAtt) 'Place attachments array, too
k = 0 'reinitialize k variable
Else
If CDate(arr2(i, 11)) > CDate(dict(arr2(i, 1))(1)) Then 'Change the item only in case of a more recent Date
Erase arrAtt: ReDim arrAtt(7) 'erase the previous loaded array
For j = 0 To UBound(arrAtt)
If arr2(i, 17 + j) <> "" Then
arrAtt(k) = arr2(i, 17 + k): k = k + 1
Else
Exit For
End If
Next j
If k > 0 Then ReDim Preserve arrAtt(k - 1)
dict(arr2(i, 1)) = Array(arr2(i, 2), arr2(i, 11), arrAtt) 'Place attachments array, too
k = 0
End If
End If
End If
Next i
'Place the necessary data in its place:
For i = 1 To UBound(arr1)
If dict.Exists(arr1(i, 1)) Then
arr1(i, 19) = dict(arr1(i, 1))(0) 'extract first item array element
For j = 0 To UBound(dict(arr1(i, 1))(2)) 'extract existing URLs
If dict(arr1(i, 1))(2)(j) = "" Then Exit For 'exit the loop in case of empty strings
arr1(i, 20 + j) = dict(arr1(i, 1))(2)(j) 'place the URLs in their position
Next j
Else
arr1(i, 19) = "NA"
End If
Next i
rng1.Value2 = arr1 'drop back the updated array content
ws1.Activate
' wb2.Close SaveChanges:=False
Application.ScreenUpdating = True
MsgBox "Ready..."
End Sub
But, if you intend to adapt wb2 workbook in terms of clearing some URLs (for the latest closing Date) , the code should be adapted to preliminarily clear the range "S:AA" in wb1 till the end of the sheet. Otherwise, existing URLs may remain from the previous run
Credit for code is for few editors in Mr . Excel forum. This code works like a charm, but I need it to copy the entire row of the new data, rather than only values from column A. Now I tried to play with true and false statements and etc. but to no avail, I believe it is out of my scope and id like so suggestions or assistance how to achieve my mission. I have simple values, no formulas, just some named columns and thousands of rows in original file and extract file.
Sub AddMissingItems()
Dim Dic As Object
Dim Arr() As Variant, outArr() As Variant
Dim i As Long, k As Long, iRow As Long
Dim c as long
Set Dic = CreateObject("Scripting.dictionary")
With Sheets("Sheet1")
c = .Cells(1, Columns.Count).End(xlToLeft).Column
Arr = .Range("A1:A" & .Range("A" & .Rows.Count).End(xlUp).Row).Value
For i = 1 To UBound(Arr, 1)
If Dic.exists(Arr(i, 1)) = False Then
Dic.Add (Arr(i, 1)), ""
End If
Next
End With
With Workbooks("ExtractFile").Worksheets("Sheet1")
Arr = .Range("A1:A" & .Range("A" & .Rows.Count).End(xlUp).Row).Value
ReDim outArr(1 To UBound(Arr), 1 To 1)
For i = 1 To UBound(Arr)
If Dic.exists(Arr(i, 1)) = False Then
k = k + 1
outArr(k, 1) = Arr(i, 1)
End If
Next
End With
iRow = Sheets("Sheet1").Range("A" & Rows.Count).End(3).Row + 1
If k <> 0 Then
Sheets("Sheet1").Range("A" & iRow).Resize(k).Value = outArr
k = 0
End If
End Sub
Tried adding Entirerow statement to several places, but to no avail.
Please, try the next adapted code. I commented where I input new variables/code lines:
Sub AddMissingItems()
Dim Dic As Object, Arr() As Variant, outArr() As Variant
Dim i As Long, k As Long, iRow As Long, c As Long
Dim r As Long, j As Long
Set Dic = CreateObject("Scripting.dictionary")
With Sheets("Sheet1")
Arr = .Range("A1:A" & .Range("A" & .rows.count).End(xlUp).row).Value
For i = 1 To UBound(Arr, 1)
If Dic.Exists(Arr(i, 1)) = False Then
Dic.Add (Arr(i, 1)), ""
End If
Next
End With
With Workbooks("ExtractFile.xlsx").Worksheets("Sheet1")
c = .cells(1, Columns.count).End(xlToLeft).column
r = .Range("A" & .rows.count).End(xlUp).row 'calculate the last row in A:A, too
Arr = .Range("A1", .cells(r, c)).Value 'place in the array all existing columns
ReDim outArr(1 To UBound(Arr), 1 To c) 'extend the redimmed array to all columns
For i = 1 To UBound(Arr)
If Dic.Exists(Arr(i, 1)) = False Then
k = k + 1
For j = 1 To c 'iterate between all array columns:
outArr(k, j) = Arr(i, j) 'place the value from each column
Next j
End If
Next
End With
iRow = Sheets("Sheet1").Range("A" & rows.count).End(3).row + 1
If k <> 0 Then
Sheets("Sheet1").Range("A" & iRow).Resize(k, UBound(Arr, 2)).Value = outArr 'resize by columns, too
k = 0
End If
End Sub
Please, send some feedback after testing it.
The purpose is to open a workbook from SharePoint, set the auto filter, copy filtered range into the existing sheet.
The two longest pieces are opening the workbook and pasting as values.
I want to store the filtered range in the array and then assign this array to the existing worksheet (instead of copy - paste).
I have another module from which I am running all the subs (this is one of them). In that module I am starting with the below.
Public Sub TurnOffFunctionality()
Application.Calculation = xlCalculationManual
Application.DisplayStatusBar = False
Application.EnableEvents = False
Application.ScreenUpdating = False
End Sub
Sub OpenWorkbookWithPopulation()
strFilePath = *Path to the SharePoint*
period = 202009
file = period & "_FR05_GRIR_Population"
strFileName = file & ".xlsb"
Set wbkopen = Workbooks.Open(strFilePath & strFileName, ReadOnly:=True, UpdateLinks:=False)
With Workbooks(file)
.Worksheets("ERP Extract").AutoFilterMode = False
.Worksheets("ERP Extract").Range("A1").AutoFilter
.Worksheets("ERP Extract").Range("A1").AutoFilter field:=17, Criteria1:="Trade"
.Worksheets("ERP Extract").Range("A1").AutoFilter field:=18, Criteria1:=">" & 90
.Worksheets("ERP Extract").AutoFilter.Range.Copy
cockpit = .Worksheets("Cockpit").Range("C6:C12").Value2
End With
With Workbooks("Master_Template_Working")
.Worksheets("Aged GRNI_Pop").Range("A1").PasteSpecial xlPasteValues
.Worksheets("Instructions").Range("C38:C44") = cockpit
End With
Workbooks(file).Close SaveChanges:=False
End Sub
You can try something like this (not tested):
With Workbooks(file)
With .Worksheets("ERP Extract")
.AutoFilterMode = False
Dim Data As Variant
' If this doesn't work, use another way.
Data = .Range("A1").CurrentRegion.Value
End With
cockpit = .Worksheets("Cockpit").Range("C6:C12").Value2
End With
Dim ColumnsCount As Long
ColumnsCount = UBound(Data, 2)
Dim i As Long ' Source Rows Counter
Dim j As Long ' Columns Counter
Dim k As Long ' Destination Rows Counter
k = 1 ' account for headers (i = 2 To ...)
For i = 2 To UBound(Data, 1)
If Data(i, 17) = "Trade" And Data(i, 18) > 90 Then
k = k + 1
For j = 1 To ColumnsCount
Data(k, j) = Data(i, j)
Next j
End If
Next i
With Workbooks("Master_Template_Working")
With .Worksheets("Aged GRNI_Pop").Range("A1")
.Resize(k, ColumnsCount).Value = Data
End With
.Worksheets("Instructions").Range("C38:C44") = cockpit
End With
My goal is to select a column of about 300,000 cells and round each cell's value to two decimal places.
I found that looping an array is far faster than looping through cells.
It is much faster if I have the whole array post its data into the cells after the loop rather than during because again posting any data in a loop takes too much time.
Is there a way to write all the values from the new array ("varArray") after the loop is completed?
Sub RoundedTwoDecimalPlaces()
Dim i As Integer
Dim MyArray() As Variant ' Declare dynamic array.
Dim LastRow As Integer
Dim lStart As Double
Dim lEnd As Double
lStart = Timer
LastRow = Cells(1, Selection.Column).End(xlDown).Row
MyArray = Range("a1:a8").Value2
ReDim MyArray(LastRow) ' Resize to x amount of elements.
For i = 1 To LastRow
MyArray(i) = Round(Cells(i, Selection.Column), 2) ' Initialize array.
Next i
''this is where I can't get my array to post into the cells dynamically.
Selection.Value = MyArray()
''to see the amount of time it takes to finish.
'' My goal is to do 300,000 lines quickly
lEnd = Timer
Debug.Print "Duration = " & (lEnd - lStart) & " seconds"
End Sub
You can get the array directly from the range and then restore the altered values:
Sub RoundedTwoDecimalPlaces()
Dim i As Integer
Dim arr As Variant
Dim lStart As Double
Dim ws As Worksheet, col as Long
Set ws = ActiveSheet
col = Selection.Column
lStart = Timer
With ws.Range(ws.Cells(1, col), ws.Cells(1, col).End(xlDown))
arr = .Value
For i = 1 to Ubound(arr, 1)
arr(i, 1) = Round(arr(i, 1), 2)
Next i
.Value = arr
end with
Debug.Print "Duration = " & (Timer - lStart) & " seconds"
End Sub
Here is how I did it using #Tim Williams Code.
I had to loop it because the array has a max character limit.
Here is the finished code:
Sub loopthrough()
Dim i As Integer
Dim arr As Variant
Dim arr1 As Variant
Dim arr2 As Variant
Dim lStart As Double
Dim ws As Worksheet, col As Long
LastRow = Cells(1, Selection.Column).End(xlDown).Row
Set ws = ActiveSheet
col = Selection.Column
lStart = Timer
If LastRow < 30001 Then
With ws.Range(ws.Cells(1, col), ws.Cells(1, col).End(xlDown))
arr = .Value2
For i = 1 To UBound(arr, 1)
If IsNumeric(arr(i, 1)) Then
arr(i, 1) = Round(arr(i, 1), 2)
Else
arr(i, 1) = arr(i, 1)
End If
Next i
.Value2 = arr
End With
Else ''if selection is more than 30,000 lines.
n = 1
Z = 30000
Do While Z < LastRow
With ws.Range(ws.Cells(n, col), ws.Cells(Z, col))
arr = .Value2
For i = 1 To UBound(arr, 1)
If IsNumeric(arr(i, 1)) Then
arr(i, 1) = Round(arr(i, 1), 2)
Else
arr(i, 1) = arr(i, 1)
End If
Next i
.Value2 = arr
End With
n = n + 30000
Z = Z + 30000
Loop
With ws.Range(ws.Cells(n, col), ws.Cells(n, col).End(xlDown))
arr = .Value2
For i = 1 To UBound(arr, 1)
If IsNumeric(arr(i, 1)) Then
arr(i, 1) = Round(arr(i, 1), 2)
Else
arr(i, 1) = arr(i, 1)
End If
Next i
.Value2 = arr
End With
End If
Debug.Print "Duration = " & (Timer - lStart) & " seconds"
End Sub
I have a problem with a selfmade vba-code. The makro should solve the following problem: I use a "cockpitfile" It should load the elemts of two worksheets from two different Excel files into two Arrays. The Elements of these Arrays should be subtracted from each other. I want to get the difference from these two elements. As an example: ArrayElm1(1,1) - ArrayElm2(1,1) = ArrayElm3(1,1), ArrayElm1(1,2) - ArrayElm2(1,2) = ArrayElm3(1,2) etc.
On the first sight the code seems to work but when I check the results with my calculater the difference of the elements is wrong. Maybe there is a problem with the UBound because in my Ubound is only Array A?
Hope you can help me!
Sub Differenz1()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'Variabledefinition
Dim i As Long 'Index
Dim j As Long 'Index
Dim k As Long 'Index
Dim ArrayA As Variant 'Array
Dim ArrayB As Variant 'Array
Dim ArrayC(71, 25) As Variant 'Array
Dim myFile1 As String 'Workbookname
Dim myFile2 As String 'Workbookname
Dim wb1 As String 'Workbookname
Dim wb2 As String 'Workbookname
Dim WS_Count1 As Integer 'Count Worksheets
Dim WS_Count2 As Integer 'Count Worksheets
Dim arrays1 As String 'Dimension
Dim arrays2 As String 'Dimension
'Change the actual path
ChDrive "O:\"
ChDir "O:..."
myFile1 = Application.GetOpenFilename
Workbooks.Open Filename:=myFile1, ReadOnly:=True, IgnoreReadOnlyRecommended:=True
wb1 = ActiveWorkbook.Name
WS_Count1 = ActiveWorkbook.Worksheets.Count
myFile2 = Application.GetOpenFilename
Workbooks.Open Filename:=myFile2, ReadOnly:=True, IgnoreReadOnlyRecommended:=True
wb2 = ActiveWorkbook.Name
WS_Count2 = ActiveWorkbook.Worksheets.Count
For k = 1 To WS_Count1
ArrayA = Workbooks(wb1).Worksheets(k).Range("F5:Y75").Value
ArrayB = Workbooks(wb2).Worksheets(k).Range("F5:Y75").Value
For i = LBound(ArrayA, 1) To UBound(ArrayA, 1)
For j = LBound(ArrayA, 2) To UBound(ArrayA, 2)
If Not IsError(ArrayA(i, j)) And Not IsError(ArrayB(i, j)) Then ArrayC(i, j) = ArrayA(i, j) - ArrayB(i, j)
Next j
Next i
ThisWorkbook.Worksheets(k + 1).Range("F5:Y75").Value = ArrayC
Next k
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
You almost had it right, but the issues was that you didn't reset ArrayC
This code creates new sheets in ThisWorkbook for subtractions, and based on your previous question it checks for errors, and performs the subtractions only if both values are numbers
Option Explicit
Public Sub Differenz2()
Const USED_RNG = "F5:Y75" 'Main range
Dim i As Long, j As Long, k As Long, file1 As String, file2 As String, ws1Count As Long
Dim wb1 As Workbook, wb2 As Workbook, arr1 As Variant, arr2 As Variant, arr3 As Variant
'ChDrive "O:\": ChDir "O:..."
file1 = Application.GetOpenFilename: If file1 = "False" Then Exit Sub
file2 = Application.GetOpenFilename: If file2 = "False" Then Exit Sub
Application.ScreenUpdating = False
Set wb1 = Workbooks.Open(Filename:=file1, ReadOnly:=True)
Set wb2 = Workbooks.Open(Filename:=file2, ReadOnly:=True)
ws1Count = wb1.Worksheets.Count
If ws1Count = wb2.Worksheets.Count Then
MakeNewWS ws1Count 'Remove this line if ThisWorkbook is properly setup
For k = 1 To ws1Count
arr1 = wb1.Worksheets(k).Range(USED_RNG).Value
arr2 = wb2.Worksheets(k).Range(USED_RNG).Value
ReDim arr3(1 To 71, 1 To 20) 'reset array, based on USED_RNG ("F5:Y75")
For i = LBound(arr1, 1) To UBound(arr1, 1)
For j = LBound(arr1, 2) To UBound(arr1, 2)
If Not IsError(arr1(i, j)) And Not IsError(arr2(i, j)) Then
If IsNumeric(arr1(i, j)) And IsNumeric(arr2(i, j)) Then
arr3(i, j) = arr1(i, j) - arr2(i, j)
End If
End If
Next
Next
ThisWorkbook.Worksheets(k + 1).Range(USED_RNG) = arr3
Next
End If
wb1.Close False: wb2.Close False: ThisWorkbook.Worksheets(2).Activate
Application.ScreenUpdating = True
End Sub
Private Sub MakeNewWS(ByVal wsCount As Long)
Dim i As Long, ws As Worksheet
With ThisWorkbook.Worksheets
Application.DisplayAlerts = False
For Each ws In ThisWorkbook.Worksheets
If Left(ws.Name, 12) = "Subtraction " Then
If .Count = 1 Then .Add
ws.Delete
End If
Next
Application.DisplayAlerts = True
For i = 2 To wsCount + 1
.Add After:=ThisWorkbook.Worksheets(.Count)
ThisWorkbook.Worksheets(.Count).Name = "Subtraction " & i - 1
Next
End With
End Sub
You can ignore the MakeNewWS() sub if ThisWorkbook contains the proper number of sheets
Also, using arrays does improve performance (significantly)