When I run my code, it freezes, however it will work when I insert Application.Wait (Now + TimeValue("0:00:02")), it works perfectly. I am just wondering why it does that. This is the first time something like this has happened. Any help would be appreciated. Thanks!
Public Sub Run()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Call Import
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Private Sub Import()
Dim fd As FileDialog
Dim FileChosen As Integer
Dim FileName As String
Dim tempWB As Workbook
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.InitialFileName = "X:\Dump Report for Loans"
fd.InitialView = msoFileDialogViewList
fd.AllowMultiSelect = True
FileChosen = fd.Show
If FileChosen = -1 Then
Call Sort
Application.Wait (Now + TimeValue("0:00:02")) 'Heres where it trips
Call Save_As
Else:
Exit Sub
End If
End Sub
Private Sub Sort()
Dim fd As FileDialog
Dim tempWB As Workbook
Dim i As Integer
Dim rwCnt As Long
Dim rngSrt As Range
Dim shRwCnt As Long
Set fd = Application.FileDialog(msoFileDialogFilePicker)
For i = 1 To fd.SelectedItems.Count
Set tempWB = Workbooks.Open(fd.SelectedItems(i))
With tempWB.Worksheets(1)
rwCnt = .Cells(Rows.Count, 1).End(xlUp).Row
If .Range("A1") <> "* as of *" Then
If .Cells(rwCnt - 1, 1).NumberFormat = "mmm d, yyyy" Then
.Range("A1") = .Range("A1").Value & " as of " & .Cells(rwCnt - 1, 1)
.Rows(rwCnt - 1 & ":" & rwCnt).Delete shift:=xlShiftUp
rwCnt = rwCnt - 2
End If
End If
Set rngSrt = .Range("A2:AR" & rwCnt)
With .Sort
.SortFields.Clear
.SortFields.Add Key:=Range("E2:E" & rwCnt), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange rngSrt
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
.Columns("F:F").Insert shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
For x = rwCnt To 4 Step -1
.Cells(x, 6).Value2 = (.Cells(x, 5).Value2 - .Cells(x - 1, 5).Value2)
Next x
For Z = rwCnt To 3 Step -1
If .Cells(Z, 6).Value = 0 Then
.Rows(Z).Delete shift:=xlShiftUp
End If
Next Z
.Columns("F:F").Delete
.Columns("A:AR").AutoFit
Organize fd, tempWB, i, rwCnt
Summary fd, tempWB, i
End With
Next i
tempWB.Worksheets(2).Activate
tempWB.Worksheets(1).Visible = xlSheetHidden
End Sub
Private Sub Organize(fd As FileDialog, tempWB As Workbook, i As Integer, rwCnt As Long)
Dim rngSrt As Range
Dim shRwCnt As Long
With tempWB.Worksheets(1)
rwCnt = .Cells(Rows.Count, 1).End(xlUp).Row
.Range("A1") = .Range("A1").Value & " as of " & .Cells(rwCnt - 1, 1)
.Rows(rwCnt - 1 & ":" & rwCnt).Delete shift:=xlShiftUp
rwCnt = rwCnt - 2
Set rngSrt = .Range("A2:AR" & rwCnt)
With .Sort
.SortFields.Clear
.SortFields.Add Key:=Range("AR2:AR" & rwCnt), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SortFields.Add Key:=Range("E2:E" & rwCnt), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange rngSrt
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
For x = rwCnt To 3 Step -1
If .Cells(x, 5).Value = .Cells(x - 1, 5).Value Then
.Rows(x).Delete shift:=xlShiftUp
End If
Next x
rwCnt = .Cells(Rows.Count, 1).End(xlUp).Row
For y = 3 To rwCnt
Dim WsDest As Worksheet
Set WsDest = Nothing
On Error Resume Next 'try to find the worksheet
Set WsDest = Worksheets(Left$(.Cells(y, 44).Value, 31)) 'worksheet names are limited to 31 characters
On Error GoTo 0 're-activate error reporting
If WsDest Is Nothing Then 'if ws does not exist
'add this sheet name it and copy/paste
Set WsDest = Worksheets.Add(, Worksheets(Sheets.Count))
WsDest.Name = Left$(.Cells(y, 44).Value, 31) 'worksheet names are limited to 31 characters
.Range("A1:AR2").Copy
WsDest.Cells(1, 1).PasteSpecial Paste:=xlPasteAllUsingSourceTheme, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
.Rows(y).Copy
WsDest.Cells(3, 1).PasteSpecial Paste:=xlPasteAllUsingSourceTheme, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
WsDest.Tab.ColorIndex = 3
WsDest.Columns("A:AR").AutoFit
Else
'find last used row and copy/paste
shRwCnt = WsDest.Cells(WsDest.Rows.Count, 1).End(xlUp).Row
.Rows(y).Copy
WsDest.Cells(shRwCnt + 1, 1).PasteSpecial Paste:=xlPasteAllUsingSourceTheme, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
WsDest.Columns("A:AR").AutoFit
End If
Next y
.Columns("A:AR").AutoFit
End With
tempWB.Worksheets(1).Activate
End Sub
Private Sub Summary(fd As FileDialog, tempWB As Workbook, i As Integer)
Dim x As Integer
Dim wb As Workbook: Set wb = tempWB
Dim strName As String: strName = "Summary"
Dim ws As Worksheet
Set ws = wb.Sheets.Add(Type:=xlWorksheet, after:=wb.Worksheets(1))
Dim rwCnt As Long
Dim PCsht As Worksheet
With ws
.Name = strName
For x = 3 To Sheets.Count
Set PCsht = tempWB.Worksheets(x)
rwCnt = PCsht.Cells(Rows.Count, 1).End(xlUp).Row
.Cells(x, 1) = PCsht.Name
.Cells(x, 2) = WorksheetFunction.Sum(Range(PCsht.Cells(3, 11), PCsht.Cells(rwCnt, 11)))
Next x
.Cells(2, 1) = "Purpose Code"
.Cells(2, 2) = "Net Active Principle Balance"
.Cells(Sheets.Count + 1, 1) = "TOTAL"
.Cells(Sheets.Count + 1, 2) = WorksheetFunction.Sum(Range(ws.Cells(3, 2), ws.Cells(Sheets.Count, 2)))
.Columns("A:B").AutoFit
.Range(.Cells(3, 2), Cells(Sheets.Count + 1, 2)).NumberFormat = "$#,##0.00"
End With
End Sub
Private Sub Save_As()
Dim bFileSaveAs As Boolean
bFileSaveAs = Application.Dialogs(xlDialogSaveAs).Show
If Not bFileSaveAs Then MsgBox "User cancelled", vbCritical
End Sub
Related
having 25 columns and n number rows in sheet Input_Excel as in the image "DATA" and transposing the same into another sheet as in the image "Output" in my requited specific format . My code is working perfectly when the input_excel having minimal data and giving expected output where as the data being more than 2600 is giving bad output as in the image "Wrong"
I am hanging and struggling a lot to fix the issue. please help me to find out the problem in my below code. is there any maximum limit in handling arrays in excel VBA?
Correct me if am dealing any wrong method/calling. will be a great help and thanks in advance.
Dim ws As Worksheet
Dim toWs As Worksheet
Dim vDB, vR()
Dim strShName As Variant
Dim r As Long, i As Long, n As Long, lastRow As Long, cc As Long, req_id As String
Dim k As Integer, j As Integer
Dim sc As Range, lr As Long, lc As Long, rg As Range, myRange As Range
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Application.ScreenUpdating = False
Set ws = Sheets("Input Excel")
Set sc = ws.Range("A1")
lr = sc.SpecialCells(xlCellTypeLastCell).Row
lc = sc.SpecialCells(xlCellTypeLastCell).Column
strShName = ActiveSheet.Name
If strShName = "Data" Then
Application.DisplayAlerts = False
Sheets("Data").Delete
Application.DisplayAlerts = True
End If
Sheets.Add.Name = "Data"
Columns("A:c").Select
Selection.NumberFormat = "#"
Range("A1").Select
Set rg = ws.Range("A1").CurrentRegion
Set toWs = Sheets("Data") '<~~ Result Sheet
ws.Activate
Range("D1:Y1").Select
Selection.NumberFormat = "0"
Range("A1").Select
toWs.Activate
vDB = ws.Range(sc, ws.Cells(lr, lc)).Value
r = UBound(vDB, 1)
cc = ws.Range(sc, ws.Cells(lr, lc)).Columns.Count
For i = 2 To r
If vDB(i, 1) <> "" Then ' row
For j = 4 To cc
n = n + 1
ReDim Preserve vR(1 To cc, 1 To n)
For k = 1 To 3
vR(k, n) = vDB(i, k)
Next k
vR(4, n) = vDB(1, j)
vR(5, n) = vDB(i, j)
Next j
End If
Next i
With toWs
.UsedRange.Offset(1).Clear
.Range("A2").Resize(n, 10) = WorksheetFunction.Transpose(vR)
End With
Range("A3:C3").Select
Selection.Copy
Range("A2").Select
ActiveCell.PasteSpecial
Range("A1").Value = "Sales Org"
Range("B1").Value = "Soldto"
Range("C1").Value = "TE Part Number"
Range("D1").Value = "Demand_Date"
Range("E1").Value = "Values"
toWs.Select
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Set myRange = Range("E2:E" & lastRow)
myRange.Select
On Error GoTo eh
Selection.SpecialCells(xlCellTypeBlanks).Select
Selection.EntireRow.Delete
eh:
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Set myRange = Range("d2:d" & lastRow)
Range("J1").Select
ActiveCell.FormulaR1C1 = "=IFERROR(FIND(""."",R[1]C[-6],1),0)"
Range("J1").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
If Range("J1").Value > 0 Then
myRange.Select
Selection.Replace What:=".", Replacement:="/", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=True
End If
Range("J1").Select
Selection.ClearContents
Columns("E:E").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("E2").Select
ActiveCell.FormulaR1C1"=
DAY(RC[-1])&""/""&MONTH(RC[-1])&""/""&YEAR(RC[-1])"
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Set myRange = Range("E2:E" & lastRow)
myRange.Select
Selection.FillDown
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks:=False, Transpose:=False
Range("D1").Select
Application.CutCopyMode = False
Selection.Copy
Range("E1").Select
ActiveSheet.Paste
Columns("D:D").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
Range("f2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-5]=""NA"",RC[-5],IF(LEN(RC[-5])=
2,CONCAT(""00"",RC[-5]),IF(LEN(RC[-5])=3,
CONCAT(0,RC[-5]),IF(LEN(RC[-5])=1,CONCAT(""000"",RC[-5]),RC[-5]))))"
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Set myRange = Range("F2:F" & lastRow)
myRange.Select
Selection.FillDown
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks:=False, Transpose:=False
myRange.Select
Selection.Copy
Range("A2").Select
ActiveSheet.Paste
Columns("F:f").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
Dim v As Integer
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Range("A:E").EntireColumn.AutoFit
req_id = InputBox("Please enter request ID which is generated in your
application")
If req_id = "" Then
Application.DisplayAlerts = False
Sheets("Data").Delete
Application.DisplayAlerts = True
End If
Sheets("SaveFile").Select
End If
Range("F1").Select
ActiveCell.FormulaR1C1 = "Case_ID"
Range("F2").Select
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Set myRange = Range("F2:F" & lastRow)
myRange.Value = req_id
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Set myRange = Range("A1:F" & lastRow)
myRange.Select
Dim t As Integer
If t = 0 Then
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End If
t = 1
Set myRange = Range("A2:B" & lastRow)
myRange.Replace What:="NA", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Range("D1").Value = "Demand_Date"
Dim DTAddress As String
DTAddress = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\"
ActiveWorkbook.SaveAs Filename:=DTAddress & req_id &
"_Upload_LTF_Monthly", FileFormat:=6
MsgBox "Please check file is saved in your desktop and upload the same
desktop saved file"
ws.Activate
Range("D1:Y1").Select
Selection.NumberFormat = "mmm-yy"
Range("A1").Select
toWs.Activate
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.ScreenUpdating = True
'ActiveWorkbook.Close False
End Sub
DATA
Output
Wrong
Transpose Data Range Using Arrays
Adjust the values in the constants section (Source, Target and Other).
I've added the headers to be copied to column "H". If you don't want them copied, remove the 3rd element (, "H") in tgtCols and delete the line Target(2)(k, 1) = Source(1, j).
The Code
Option Explicit
Sub transposeDataOnly()
' Source
Const srcName As String = "Input_Excel"
Const srcFirstCell As String = "A1"
Const srcFirstCol As Long = 3
' Target
Const tgtName As String = "Data"
Dim tgtCols As Variant
tgtCols = VBA.Array("C", "E", "H") ' 'VBA' ensures zero-based.
Const tgtFirstRow As Long = 2
' Other
Dim wb As Workbook
Set wb = ThisWorkbook ' The workbook containing this code.
' Write values from Source Range to Source Array.
Dim src As Worksheet
Set src = wb.Worksheets(srcName)
Dim Source As Variant
Source = src.Range(srcFirstCell).CurrentRegion.Value
' Define Jagged Target Array.
Dim ubC As Long: ubC = UBound(tgtCols)
Dim Target As Variant: ReDim Target(0 To ubC)
Dim ubS1 As Long: ubS1 = UBound(Source, 1)
Dim ubS2 As Long: ubS2 = UBound(Source, 2)
Dim Help As Variant
ReDim Help(1 To (ubS1 - 1) * (ubS2 - srcFirstCol), 1 To 1)
Dim j As Long ' Columns Array Element Counter, Source Array Columns Counter
For j = 0 To ubC
Target(j) = Help
Next j
' Write values from Source Array to arrays of Jagged Target Array.
Dim i As Long ' Source Array Rows Counter
Dim k As Long ' Arrays of Jagged Target Array Rows Counter
For i = 2 To ubS1
If Not IsEmpty(Source(i, srcFirstCol)) Then
For j = srcFirstCol + 1 To ubS2
If Not IsEmpty(Source(i, j)) Then
k = k + 1
Target(0)(k, 1) = Source(i, srcFirstCol) ' TE Part Number
Target(1)(k, 1) = Source(i, j) ' Values
Target(2)(k, 1) = Source(1, j) ' Headers
End If
Next j
End If
Next i
' Write values from Jagged Target Array to Target Range.
Dim tgt As Worksheet
Set tgt = wb.Worksheets(tgtName)
'tgt.Cells.ClearContents
For j = 0 To ubC
tgt.Cells(tgtFirstRow, tgtCols(j)).Resize(k).Value = Target(j)
Next j
End Sub
I have a piece of modified code which I've been using but is very inefficient. The intention was to check if records in 'Database1' sheet exists in 'Log1' if so do nothing if not add the record to first available row. There are multiple iterations of a record in Log1. There should always only be one instance of the record in Database1.
Each time the code runs it replaces all records in Database1.
It seems to be cheking row1 database1 versus row1 Log1 and not the whole range so it copies in multiple entries for one record even though it already exists.
Can anyone help? Apologies if I don't articulate this clearly please ask and I will add more detail if needed.
Option Explicit
Sub Checkrecordthenaddifnotexists()
Dim Ws As Worksheet
Dim i As Long, j As Long
Dim k As Long
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Dim objTable As ListObject
Application.Calculation = xlCalculationAutomatic
Set sht = Worksheets("Database1")
Sheets("Database1").Select
Cells.Select
sht.Sort.SortFields.Clear
sht.Sort.SortFields.Add Key:=Range("A:A"), _
SortOn:=xlSortOnValues, Order:=xlAscending, _
DataOption:=xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("Database1").Sort
.SetRange Range("A:AB")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Sheets("Log1").Select
Cells.Select
ActiveWorkbook.Worksheets("Log1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Log1").Sort.SortFields.Add Key:=Range("B:B"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Log1").Sort
.SetRange Range("A:AJ")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
sht.Activate
Set StartCell = Range("A2")
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
On Error Resume Next
'Sheet2.ShowAllData
Sheet2.Select
Selection.AutoFilter
On Error GoTo 0
sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select
Set objTable = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
With ActiveSheet
.ListObjects(1).Name = "Database_v0.1"
End With
Set Ws = Sheets("Database1")
Dim RowsMaster As Integer, Rows2 As Integer
RowsMaster = Ws.Cells(1048576, 1).End(xlUp).Row
Rows2 = Worksheets("Log1").Cells(1048576, 2).End(xlUp).Row
With Worksheets("Log1")
For i = 2 To Rows2
For j = 2 To RowsMaster + 1
If .Cells(i, 1) = Ws.Cells(j, 1) Then
Exit For
End If
Next j
If j = RowsMaster + 1 Then
RowsMaster = RowsMaster + 1
For k = 2 To 8
Ws.Cells(RowsMaster, k - 1) = .Cells(i, k)
Next
End If
Next i
End With
Sheets("Database1").Activate
ActiveSheet.ListObjects("Database_v0.1").Unlist
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Range("A1:NT1048576").RemoveDuplicates Columns:=1, Header:=xlYes
Sheets("Database Repository").Columns("A").Select
Selection.NumberFormat = "0"
Sheet2.Select
Selection.AutoFilter
Application.Calculation = xlCalculationAutomatic
End Sub
Well this should help you, the whole explanation is in the code:
Option Explicit
Sub Checkrecordthenaddifnotexists()
Application.Calculation = xlCalculationAutomatic
'Try to declare your variables where you are using them
'You sort 2 times, different sheets but mostly same way so,
'write another procedure with variable and give them as you need
'the procedure below needs:
'sheet to be sorted, which range will be the one to sort, the starting cell
SortMySheet ThisWorkbook.Sheets("Database1"), "A:A", ThisWorkbook.Sheets("Database1").Range("A2")
SortMySheet ThisWorkbook.Sheets("Log1"), "A:A", ThisWorkbook.Sheets("Log1").Range("A2") 'change the starting cell
'Now we will change your approach to use 2 arrays and 1 dictionary
'For that you need to go to tools-References- and then check the Microsoft Scripting Runtime reference
'This is assuming you want to add the new entries from sheet Log1 to DataBase1 when they not exist in the later.
'The arrays:
With ThisWorkbook.Sheets("DataBase1")
Dim arrMaster As Variant: arrMaster = LoadArray(ThisWorkbook.Sheets("Database1"), .Range("A2")) 'change the starting cell
End With
With ThisWorkbook.Sheets("Log1")
Dim arrLog As Variant: arrLog = LoadArray(ThisWorkbook.Sheets("Log1"), .Range("A2")) 'change the starting cell
End With
'The dictionary:
Dim IdDictionary As Dictionary: Set IdDictionary = LoadDictionary(arrMaster)
'Now the hardwork, getting the new items to the sheet Log1
AddNewEntries arrMaster, arrLog, IdDictionary
' the next 6 lines of code are useless, we didn't need to make a table, we are not going to have duplicates
' Sheets("Database1").Activate
' ActiveSheet.ListObjects("Database_v0.1").Unlist
' Range("A1").Select
' Range(Selection, Selection.End(xlToRight)).Select
' Range(Selection, Selection.End(xlDown)).Select
' ActiveSheet.Range("A1:NT1048576").RemoveDuplicates Columns:=1, Header:=xlYes
' the next 4 lines of code I don't get
' Sheets("Database Repository").Columns("A").Select
' Selection.NumberFormat = "0"
' Sheet2.Select
' Selection.AutoFilter
Application.Calculation = xlCalculationAutomatic
End Sub
Private Sub SortMySheet(ws As Worksheet, KeyRange As String, StartCell As Range)
With ws
'Get the last row and column for your whole range
Dim LastRow As Long: LastRow = .Cells(.Rows.Count, StartCell.Column).End(xlUp).Row
Dim LastColumn As Long: LastColumn = .Cells(StartCell.Row, .Columns.Count).End(xlToLeft).Column
'Sort your whole range
.Sort.SortFields.Clear
.Sort.SortFields.Add .Range(KeyRange), xlSortOnValues, xlAscending, xlSortTextAsNumbers
With .Sort
.SetRange ws.Range(StartCell, ws.Cells(LastRow, LastColumn))
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
End Sub
Private Function LoadArray(ws As Worksheet, StartCell As Range) As Variant
With ws
Dim LastRow As Long: LastRow = .Cells(.Rows.Count, StartCell.Column).End(xlUp).Row
Dim LastColumn As Long: LastColumn = .Cells(StartCell.Row, .Columns.Count).End(xlToLeft).Column
LoadArray = .Range(StartCell, .Cells(LastRow, LastColumn))
End With
End Function
Private Function LoadDictionary(arr As Variant) As Dictionary
Set LoadDictionary = New Dictionary
'By default dictionaries are Case sensitive, if you need to check without that then:
'LoadDictionary.CompareMode = TextCompare
'Uncheck the comment from the line above, by default I'll go with case Sensitive
Dim i As Long
For i = 1 To UBound(arr)
If Not LoadDictionary.Exists(arr(i, 1)) Then LoadDictionary.Add arr(i, 1), i
Next i
End Function
Private Sub AddNewEntries(arrMaster As Variant, arrLog As Variant, IdDictionary As Dictionary)
With ThisWorkbook.Sheets("DataBase1")
Dim i As Long, j As Long
Dim LastRow As Long
'Loop through all entries in arrLog
For i = 2 To UBound(arrLog)
'If the entry doesn't exist in the DataBase sheet then
If Not IdDictionary.Exists(arrLog(i, 1)) Then
'Calculate the first free row of data in column A for DataBase1
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
'Loop through first to last column in arrLog and paste it to DataBase1
For j = 1 To UBound(arrLog, 2)
.Cells(LastRow, j) = arrLog(i, j)
Next j
End If
Next i
End With
End Sub
I know my code looks like Frankenstein for take bits around the web, but it does work on my computer. Yet, when I try to run it on another computer (that has the same Excel 2016 version), it gives me
run-time error '9': subscription out of range
Why?
I have been doing some iterations such as removing activeworkbook to deal with various error it was giving but the error keeps changing. In addition, this time, the VBA debugger does not even give me a yellow line to check.
Sub CombineAll()
'Stop, delete sheet and activate Alerts
Application.DisplayAlerts = False
Sheets("Programmation générale").Delete
Application.DisplayAlerts = True
'Insert a new worksheet. Assign it to a name. Place it before Index
Set NewWs = Worksheets.Add(Before:=Worksheets("Index"))
NewWs.Name = "Programmation générale"
'Loop to copy worksheets
NextRow = 1
For Each ws In ThisWorkbook.Worksheets
If Not NewWs.Name = ws.Name Then
If Not Sheet1.Name = ws.Name Then
finalRow = ws.Cells(Rows.Count, 1).End(xlUp).Row - 1
ws.Cells(2, 1).Resize(finalRow, 14).Copy NewWs.Cells(NextRow, 1)
NextRow = NextRow + finalRow
End If
End If
Next ws
'Copy header
Sheet3.Range("A1:N1").Copy
NewWs.Range("A1").Rows("1:1").Insert Shift:=xlDown
'Select the new worksheet and transform into table
NewWs.Select
Dim src As Range
Set src = Range("B5").CurrentRegion
Set NewWs = ActiveSheet
NewWs.ListObjects.Add(SourceType:=xlSrcRange, Source:=src, _
xlListObjectHasHeaders:=xlYes, tablestyleName:="TableStyleMedium15").Name = "ProgrammationGenerale"
'Arrange the table to specifications
Range("ProgrammationGenerale[#All]").Select
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveSheet.Columns("A:N").AutoFit
Dim finalRowTable As Integer
Dim i As Integer
finalRowTable = Cells(Rows.Count, 1).End(xlUp).Row
Range("A1:A" & finalRow).EntireRow.AutoFit
For i = 2 To finalRow
If Range("A" & i).EntireRow.RowHeight < 27 Then
Range("A" & i).EntireRow.RowHeight = 27
End If
Next if
ActiveSheet.Range("D:F").EntireColumn.Hidden = True
ActiveSheet.Range("H:J").EntireColumn.Hidden = True
With ThisWorkbook.Worksheets("Programmation générale").ListObjects("ProgrammationGenerale").Sort
.SortFields.Clear
.SortFields.Add _
Key:=.Parent.ListColumns("Début_Date").DataBodyRange, SortOn:=xlSortOnValues, Order:= _
xlAscending, DataOption:=xlSortNormal
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'Arrange for printing
ActiveSheet.PageSetup.Orientation = xlLandscape
ActiveSheet.PageSetup.PaperSize = xlPaperLegal
End Sub
I've got a problem that I'm struggling to make sense of and I'm hoping you guys can assist.
My if statement is not executing the action for a true result and I'm not sure why. I have used a similar condition earlier in the code and there were no issues.
here's the section of the code that I'm struggling with:
Option Explicit
Option Base 1
Function binsearch(ByRef strArray() As String, ByRef strSearch As String) As Long
Dim lngIndex As Long
Dim lngFirst As Long
Dim lngLast As Long
Dim lngMiddle As Long
Dim bolInverseOrder As Boolean
lngFirst = LBound(strArray)
lngLast = UBound(strArray)
bolInverseOrder = (strArray(lngFirst) > strArray(lngLast))
binsearch = lngFirst - 1
Do
lngMiddle = (lngFirst + lngLast) \ 2
If strArray(lngMiddle) = strSearch Then
binsearch = lngMiddle
strSearch = strArray(lngMiddle)
Exit Do
ElseIf ((strArray(lngMiddle) < strSearch) Xor bolInverseOrder) Then
lngFirst = lngMiddle + 1
Else
lngLast = lngMiddle - 1
End If
Loop Until lngFirst > lngLast
End Function
Public Sub RE()
Dim MasterData As Variant, toFind As Variant, toFound As Variant
Dim WS As Worksheet, WS1 As Worksheet, WS2 As Worksheet, WS3 As Worksheet
Dim st_date As Date, end_date As Date, Tran_date As Date
Dim lastrow As Long, lastrow1 As Long, lastrow2 As Long, lastcol As Long, erow As Long, erow1 As Long, ecol As Long, Low As Long, Mid As Long, high As Long
Dim st_cell As Range, mydata As Range, DDT As Range, DDT1 As Range, DDT2 As Range
Dim Sheetname As String, Descr1 As String, Descr2() As String, Descr3() As String
Dim mydata1 As Variant, mydata2 As Variant, mydata3 As Variant
Dim amount1 As Currency, amount2 As Currency, amount3 As Currency
Dim i As Long
Application.ScreenUpdating = True
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\mpofa\Downloads\transactionHistory (1).csv", Destination:= _
Range("$A$1"))
.Name = "transactionHistory (1)_1"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(5, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
ActiveWorkbook.Sheets(ActiveSheet.Name).Name = "Main page"
Set WS = Sheets("main page")
Set st_cell = Sheets("main page").Range("A2")
lastrow = WS.Cells(WS.Rows.Count, st_cell.Column).End(xlUp).row
lastcol = WS.Cells(st_cell.row, WS.Columns.Count).End(xlToLeft).Column
Columns("A:A").Select
ActiveWorkbook.Worksheets("main page").sort.SortFields.Clear
ActiveWorkbook.Worksheets("main page").sort.SortFields.Add Key:=Range("A1"), _
SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("main page").sort
.SetRange Range("A:D")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Dim x As Long
For x = 0 To -2 Step -1
end_date = Sheets("main page").Range("A2").Value
st_date = DateAdd("m", x, end_date)
Worksheets.Add after:=Sheets("main page")
Dim p As Long, q As Long, y As Long
p = Worksheets.Count
For q = 1 To p
With Worksheets(q)
Sheetname = Format(st_date, "yyyy-mmm")
ActiveSheet.Name = Sheetname
End With
Sheets("Main page").Select
Range("A1:C1").Select
Selection.Copy
Sheets(Sheetname).Select
Range("A1").Select
ActiveSheet.Paste
Columns("A:A").Select
Selection.NumberFormat = "yyyy/mm/dd"
Columns("C:C").Select
Selection.NumberFormat = "R#,##0.00_);(R#,##0.00)"
Worksheets("main page").Activate
Columns("A:A").Select
Selection.NumberFormat = "yyyy/mm/dd"
Range("A2").Select
For i = 2 To lastrow
Tran_date = WS.Cells(i, 1)
If Month(Tran_date) = Month(st_date) Then
erow = Sheets(Sheetname).Cells(1, 1).CurrentRegion.Rows.Count + 1
Sheets(Sheetname).Cells(erow, 1) = WS.Cells(i, "a")
Sheets(Sheetname).Cells(erow, 2) = WS.Cells(i, "b")
Sheets(Sheetname).Cells(erow, 3) = WS.Cells(i, "c")
ecol = Sheets(Sheetname).Cells(2, Columns.Count).End(xlToLeft).Offset(0, 1).Column
End If
Sheets(Sheetname).Select
Columns("A:A").Select
Columns("A:A").EntireColumn.AutoFit
Columns("B:B").Select
Columns("B:B").EntireColumn.AutoFit
Columns("C:C").Select
Columns("C:C").EntireColumn.AutoFit
Next i
Next q
Next x
Sheets.Add after:=Sheets(Sheets.Count)
Sheets(ActiveSheet.Name).Name = "Report"
Sheets("Report").Range("A1") = "Description"
Sheets("Report").Range("B1") = "Amount"
erow1 = Sheets("report").Cells(1, 1).CurrentRegion.Rows.Count + 1
Set WS1 = ThisWorkbook.Sheets(2)
Set WS2 = ThisWorkbook.Sheets(3)
Set WS3 = ThisWorkbook.Sheets(4)
With WS1.Range("B:B")
.sort key1:=WS1.Range("B1"), Header:=xlYes
Set mydata1 = Range(.Cells(2, 2), .Cells(.Rows.Count, 1).End(xlUp))
End With
MasterData = mydata1.Value
Set DDT = WS1.Range("B2")
lastrow = WS1.Cells(WS1.Rows.Count, DDT.Column).End(xlUp).row
With WS2.Range("B:B")
.sort key1:=WS2.Range("B1"), Header:=xlYes
End With
Set DDT1 = WS2.Range("B2")
lastrow1 = WS2.Cells(WS2.Rows.Count, DDT1.Column).End(xlUp).row
With WS3.Range("B:B")
.sort key1:=WS3.Range("B1"), Header:=xlYes
End With
Set DDT2 = WS3.Range("B2")
lastrow2 = WS3.Cells(WS3.Rows.Count, DDT2.Column).End(xlUp).row
For Each WS In ThisWorkbook.Sheets
Do While WS.Name <> "main page"
For i = 2 To lastrow
Descr1 = WS1.Cells(i, 2).Text
' Set mydata2 = Range(.Cells(2, 2), .Cells(.Rows.Count, 1).End(xlUp))
For p = 2 To lastrow1
ReDim Descr2(p)
Descr2(p) = WS2.Cells(p, 2).Text
ReDim Preserve Descr2(p)
Call binsearch(Descr2(), Descr1)
' Set mydata3 = Range(.Cells(2, 2), .Cells(.Rows.Count, 1).End(xlUp))
For q = 2 To lastrow2
ReDim Descr3(q)
Descr3(q) = WS3.Cells(q, 2).Text
ReDim Preserve Descr3(q)
Call binsearch(Descr3(), Descr1)
If binsearch(Descr3(), Descr1) = 1 Then
Descr1 = Trim(Descr3(q))
Else
End If
If binsearch(Descr3(), Descr1) = 1 Then
Descr1 = Trim(Descr3(q))
Else
End If
If Descr1 = Trim(Descr3(q)) & Descr1 = Trim(Descr2(p)) Then
Sheets("report").Cells(erow1, 1) = WS1.Cells(i, "b")
Sheets("report").Cells(erow1, 2) = WS1.Cells(i, "c")
End If
Next q
Next p
Next i
Loop
Next WS
Sheets("Report").Select
Columns("A:A").Select
Columns("A:A").EntireColumn.AutoFit
Columns("B:B").Select
Columns("B:B").EntireColumn.AutoFit
End Sub
I'm getting a true condition but the cells information is not coming through into the intended sheet. I'm really stunned, please help.
Thanks in advance.
The answer is that this code is incomplete and could not run: you have not defined the loops. Please try "Debug --> Compile VBAProject"; when you get no errors there and still not the performance you look for then ask again.
I'm having an issue with this code that is suppsed to get data from another workbook and specific worksheet. It's supposed to sort and filter out data that is in Column C when I enter a specific data that I enter on my workbook. The code is working up until the sort and filter part and it seems like it's duplicating the data on my workbook instead of just filtering and pulling the data needed. Here is the code I will separate it in parts for better understanding.
Beginning of code that opens the other workbook:
The 3rd to last part of the code is what is highlighted in the debugging process, the "workbooks(mname) part towards the end.
Workbooks(mname).Sheets(msheet).Range(Cells(1, 1), Cells(1, LastCol)).Copy Destination:=Workbooks("Master_RRR.xlsm").Sheets("MGPR1").Range("A1")
I = 17
Do While Workbooks("Master_RRR.xlsm").Sheets("Master log").Cells(17, "Y").Value <> ""
mbank = Workbooks("Master_RRR.xlsm").Sheets("Master log").Cells(17, "Y").Value
match = Application.WorksheetFunction.match(mbank, Workbooks(mname).Sheets(msheet).Range("C1:C" & LastRow), 0)
repeat = Application.WorksheetFunction.CountIf(Workbooks(mname).Sheets(msheet).Range("C1:C" & LastRow), mbank)
till = Application.WorksheetFunction.CountA(Workbooks("Master_RRR.xlsm").Sheets("MGPR1").Range("C:C"))
Workbooks(mname).Sheets(msheet).Range(Cells(match, "C"), Cells(match + repeat - 1, LastCol)).Copy Destination:=Workbooks("Master_RRR.xlsm").Sheets("MGPR1").Range("A" & till + 1)
I = I + 1
Loop
Here is the beginning of the code:
Sub getdata()
Dim mastername As String
Dim count As Long
Dim match As Long
Dim repeat As Long
Dim path As String
Dim status As String
Dim name As String
Dim mpath As String
Dim cpath As String
Dim LastRow As Long
Dim LastCol As Integer
Dim mbank As String
Dim mname As String
mpath = Sheets("Master log").Cells(14, "Y").Value
mname = Sheets("Master log").Cells(15, "Y").Value
msheet = Sheets("Master log").Cells(16, "Y").Value
Sheets("MGPR1").Range("A1:AA50000").ClearContents
name = Application.ActiveWorkbook.name
cpath = Application.ActiveWorkbook.path & "\"
Windows(name).Activate
'--open Management report workbook if not already open
If CheckFileIsOpen(mname) = False Then
Workbooks.Open mpath & mname
End If
'-------------------------------------------
Windows(mname).Activate
For Each ws In ActiveWorkbook.Worksheets
ws.Visible = xlSheetVisible
If ws.Visible = True Then
End If
Next ws
Sheets(msheet).Select
'select full data
With ActiveSheet
LastRow = .Cells(.Rows.count, "A").End(xlUp).Row
End With
With ActiveSheet
' LastCol = .Cells(1, .Columns.count).End(xlToLeft).Column
LastCol = 22
End With
'--------------------- put filter
Range(Cells(1, 1), Cells(LastRow, LastCol)).Select
Selection.AutoFilter
Range("K2").Select
ActiveWorkbook.Worksheets(msheet).AutoFilter.Sort.SortFields. _
Add Key:=Range("C1:C" & LastRow), SortOn:=xlSortOnValues, Order:=xlAscending, _
DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets(msheet).AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("A1").Select
Range(Cells(1, 1), Cells(LastRow, LastCol)).Select
Selection.AutoFilter
Range("H5").Select