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.
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 am new using VBA and I've run into something that has been puzzling me: when I run a pivot on the following line of code it takes a really long time for it to finish when in reality it should not take that long. If anyone knows what the problem with it is or if you have some ways to make my code run more efficiently please let me know.
Sub Macro1()
'
' Macro1 Macro
'
' Keyboard Shortcut: Ctrl+q
'
Dim ws1 As Worksheet
Dim wb1 As Workbook
Dim ws2 As Worksheet
Dim wb2 As Workbook
Dim ws3 As Worksheet
Dim ws4 As Worksheet
Dim ws5 As Worksheet
Dim ws6 As Worksheet
Dim ws7 As Worksheet
Dim ws8 As Worksheet
Dim ws9 As Worksheet
Dim ws10 As Worksheet
Dim LastRow As Long
Dim LastRow1 As Long
Dim LastCol1 As Long
Dim PTable1 As PivotTable
Dim PCache1 As PivotCache
Dim PRange1 As Range
Set wb1 = ActiveWorkbook
Set ws1 = Sheets(1)
Set ws2 = Sheets.Add(After:=ActiveSheet)
Set ws3 = Sheets.Add(After:=ActiveSheet)
Set ws4 = Sheets.Add(After:=ActiveSheet)
Set ws5 = Sheets.Add(After:=ActiveSheet)
Set ws6 = Sheets.Add(After:=ActiveSheet)
Set ws7 = Sheets.Add(After:=ActiveSheet)
Set ws8 = Sheets.Add(After:=ActiveSheet)
Set ws9 = Sheets.Add(After:=ActiveSheet)
Set ws10 = Sheets.Add(After:=ActiveSheet)
ws2.Name = "Total"
ws3.Name = "01"
ws4.Name = "IM"
ws5.Name = "AMA"
ws6.Name = "TD"
ws7.Name = "PUP"
ws8.Name = "POS"
ws9.Name = "STG"
ws10.Name = "07"
With ActiveWindow
If .FreezePanes Then .FreezePanes = False
.SplitColumn = 0
.SplitRow = 1
.FreezePanes = True
End With
With ws1
.Cells(1, 24) = "Bin"
.Cells(1, 25) = "UN"
.Range("A:Y").AutoFilter _
Field:=13, _
Criteria1:=">=1"
LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
.Range("E1:M" & LastRow).Copy ws2.Range("A1")
.Range("A:Y").AutoFilter _
Field:=21, _
Criteria1:="=1", _
Operator:=xlOr, Criteria2:="=01DIST"
.Range("E1:M" & LastRow).Copy ws3.Range("A1")
.Range("A:Y").AutoFilter _
Field:=21, _
Criteria1:=Array("10", "20", "40", "80")
.Range("E1:M" & LastRow).Copy ws4.Range("A1")
.Range("A:Y").AutoFilter _
Field:=21, _
Criteria1:="=AMA"
.Range("E1:M" & LastRow).Copy ws5.Range("A1")
.Range("A:Y").AutoFilter _
Field:=21, _
Criteria1:="=TD"
.Range("E1:M" & LastRow).Copy ws6.Range("A1")
.Range("A:Y").AutoFilter _
Field:=21, _
Criteria1:="=STG"
.Range("E1:M" & LastRow).Copy ws9.Range("A1")
.Range("A:Y").AutoFilter _
Field:=21, _
Criteria1:="7"
.Range("E1:M" & LastRow).Copy ws10.Range("A1")
End With
LastRow1 = ws2.Cells(Rows.Count, 1).End(xlUp).Row
LastCol1 = ws2.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange1 = ws2.Range("A1").CurrentRegion
Set PCache1 = ActiveWorkbook.PivotCaches.Create(xlDatabase, PRange1)
Set PTable1 = PCache1.CreatePivotTable(ws2.Cells(1, 10), "PivotTable1")
With PTable1.PivotFields("Part Number")
.Orientation = xlRowField
.Position = 1
End With
With PTable1.PivotFields("Inventory Value")
.Orientation = xlColumnField
.Position = 1
End With
With PTable1.PivotFields("Qty OH")
.Orientation = xlColumnField
.Position = 2
End With
PTable1.AddDataField ws2.PivotTables _
("PivotTable1").PivotFields("Qty OH"), "Sum of Qty OH", xlSum
PTable1.AddDataField ws2.PivotTables _
("PivotTable1").PivotFields("Inventory Value"), "Sum of Inventory Value", xlSum
End Sub
So I was able to find a way to make my pivot table run faster than before. I think it has something to do with the PTable1.PivotFields section of my previous code, my new code, which is longer now that I figured it out works like a charm.
Sub LiveERP_Test()
'
' LiveERP_Test Macro
'
' Keyboard Shortcut: Ctrl+q
'
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
ActiveWindow.FreezePanes = True
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim ws4 As Worksheet
Dim ws5 As Worksheet
Dim ws6 As Worksheet
Dim ws7 As Worksheet
Dim ws8 As Worksheet
Dim ws9 As Worksheet
Dim ws10 As Worksheet
Dim LastRow As Long
Dim LastRow1 As Long
Dim LastCol1 As Long
Dim LastRow2 As Long
Dim LastCol2 As Long
Dim LastRow3 As Long
Dim LastCol3 As Long
Dim LastRow4 As Long
Dim LastCol4 As Long
Dim LastRow5 As Long
Dim LastCol5 As Long
Dim LastRow6 As Long
Dim LastCol6 As Long
Dim PTable1 As PivotTable
Dim PCache1 As PivotCache
Dim PRange1 As Range
Dim PTable2 As PivotTable
Dim PCache2 As PivotCache
Dim PRange2 As Range
Dim PTable3 As PivotTable
Dim PCache3 As PivotCache
Dim PRange3 As Range
Dim PTable4 As PivotTable
Dim PCache4 As PivotCache
Dim PRange4 As Range
Dim PTable5 As PivotTable
Dim PCache5 As PivotCache
Dim PRange5 As Range
Dim PTable6 As PivotTable
Dim PCache6 As PivotCache
Dim PRange6 As Range
Set ws1 = Sheets(1)
Set ws2 = Sheets.Add(After:=ActiveSheet)
Set ws3 = Sheets.Add(After:=ActiveSheet)
Set ws4 = Sheets.Add(After:=ActiveSheet)
Set ws5 = Sheets.Add(After:=ActiveSheet)
Set ws6 = Sheets.Add(After:=ActiveSheet)
Set ws7 = Sheets.Add(After:=ActiveSheet)
Set ws8 = Sheets.Add(After:=ActiveSheet)
Set ws9 = Sheets.Add(After:=ActiveSheet)
Set ws10 = Sheets.Add(After:=ActiveSheet)
ws2.Name = "Total"
ws3.Name = "01"
ws4.Name = "IM"
ws5.Name = "AMA"
ws6.Name = "TD"
ws7.Name = "PUP"
ws8.Name = "POS"
ws9.Name = "STG"
ws10.Name = "07"
With ws1
.Columns("W:W").EntireColumn.AutoFit
.Cells("1,24") = "Bin"
.Cells("1,25") = "UN"
.Range("A:Y").AutoFilter _
Field:=13, _
Criteria1:=">=1"
LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
.Range("E1:M" & LastRow).Copy ws2.Range("A1")
.Range("A:Y").AutoFilter _
Field:=21, _
Criteria1:="=1", _
Operator:=xlOr, Criteria2:="=01DIST"
.Range("E1:M" & LastRow).Copy ws3.Range("A1")
.Range("A:Y").AutoFilter _
Field:=21, _
Criteria1:=Array("10", "20", "40", "80")
.Range("E1:M" & LastRow).Copy ws4.Range("A1")
.Range("A:Y").AutoFilter _
Field:=21, _
Criteria1:="=AMA"
.Range("E1:M" & LastRow).Copy ws5.Range("A1")
.Range("A:Y").AutoFilter _
Field:=21, _
Criteria1:="=TD"
.Range("E1:M" & LastRow).Copy ws6.Range("A1")
.Range("A:Y").AutoFilter _
Field:=21, _
Criteria1:="=STG"
.Range("E1:M" & LastRow).Copy ws9.Range("A1")
.Range("A:Y").AutoFilter _
Field:=21, _
Criteria1:="7"
.Range("E1:M" & LastRow).Copy ws10.Range("A1")
.Range("U1:V" & LastRow).Copy ws10.Range("J1")
End With
LastRow1 = ws2.Cells(Rows.Count, 1).End(xlUp).Row
LastCol1 = ws2.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange1 = ws2.Range("A1").CurrentRegion
Set PCache1 = ActiveWorkbook.PivotCaches.Create(xlDatabase, PRange1)
Set PTable1 = PCache1.CreatePivotTable(ws2.Cells(1, 10), "PivotTable1")
With ws2.PivotTables("PivotTable1")
.ColumnGrand = True
.HasAutoFormat = True
.DisplayErrorString = False
.DisplayNullString = True
.EnableDrilldown = True
.ErrorString = ""
.MergeLabels = False
.NullString = ""
.PageFieldOrder = 2
.PageFieldWrapCount = 0
.PreserveFormatting = True
.RowGrand = True
.SaveData = True
.PrintTitles = False
.RepeatItemsOnEachPrintedPage = True
.TotalsAnnotation = False
.CompactRowIndent = 1
.InGridDropZones = False
.DisplayFieldCaptions = True
.DisplayMemberPropertyTooltips = False
.DisplayContextTooltips = True
.ShowDrillIndicators = True
.PrintDrillIndicators = False
.AllowMultipleFilters = False
.SortUsingCustomLists = True
.FieldListSortAscending = False
.ShowValuesRow = False
.CalculatedMembersInFilters = False
.RowAxisLayout xlCompactRow
End With
With ws2.PivotTables("PivotTable1").PivotCache
.RefreshOnFileOpen = False
.MissingItemsLimit = xlMissingItemsDefault
End With
With ws2.PivotTables("PivotTable1").PivotFields("Part Number")
.Orientation = xlRowField
.Position = 1
End With
PTable1.AddDataField ws2.PivotTables _
("PivotTable1").PivotFields("Qty OH"), "Sum of Qty OH", xlSum
PTable1.AddDataField ws2.PivotTables _
("PivotTable1").PivotFields("Inventory Value"), "Sum of Inventory Value", xlSum
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
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'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