New to arrays - Array not returning values

Beemerang

Board Regular
Joined
Sep 14, 2011
Messages
114
Hello all,

I am trying to use arrays for the first time and I am flummoxed! Although the array seems to be populating when I write the values to it, any attempt to read those values fail as nothing is returned. Now I KNOW that this is my stupidity and I have checked and rechecked the code that I cobbled together but I simply cannot see where I am going wrong. Any help would be hugely appreciated.

I would like to write the array to a range in Sheet1 but no values are returned and when I test with debug.print it seems that the array contains only 3 or 4 values instead of the dozens that were written to it. Please forgive my messy code!

Code:
'====DECLARE VARIABLES:'Declare Counter variables
'Dim x As Integer
Dim SheetCounter As Integer     'Used to count sheets
Dim MasterCount As Long         'Used to store number of unique keys
Dim RowCounter As Long          'Used to count rows in ranges
Dim TxnCounter As Integer       'Used to count transactions


'Declare Database variables
Dim UniqueKey As String         'Stores unique customer/household id
Dim MonthAdded As String        'Stores the month in which a household becomes a customer


'Declare Range variables
Dim MasterList As Range         'Holds the master list of unique keys
Dim DataRange As Range          'Holds the active range being worked on
Dim RefCell As Range            'Hold the address of the cell being referenced in a data range


'Declare Calculation variables
Dim CalcNew As Integer          'Stored calculation of new customers for a month
Dim CalcRetained As Integer     'Stores calculation of retained customers for a month
Dim KeyResult As Variant


'Declare Arrays:
Dim MasterArray As Variant      'Stores MasterArray list of unique keys
Dim TxnArray As Variant         'Stores TxnArray month's list of transactions
Dim CalcArray As Variant        'Stores results of calculations


'SET APPLICATION STATE:
'Application.ScreenUpdating = False     'To stop screen flicker
'Application.Calculation = xlCalculationManual      'Stop automatic calculation
'MsgBox Sheets.Count & "sheets in workbook"     'For testing purposes only


'INITIALISE CALCULATION ARRAY:
CalcArray = Array("Sep 2018", "Oct 2018", "Nov 2018", "Dec 2018", "Jan 2019", "Feb 2019", "Mar 2019", "Apr 2019", "May 2019", "Jun 2019", "Jul 2019", "Aug 2019")
ReDim CalcArray(Sheets.Count, 2)




'READ MASTER LIST INTO ARRAY:
Sheets("Master List").Activate
Set DataRange = ActiveSheet.Range("A1:B1", Range("B1").End(xlDown))
DataRange.Select
MasterCount = DataRange.Rows.Count
MasterArray = DataRange.Value2


'COMPARE UNIQUE IDs ON MONTHLY TRANSACTION SHEETS TO MASTER LIST:
SheetCounter = Sheets.Count
For Each Sheet In Sheets
    CalcNew = 0
    CalcRetained = 0
    If Sheets(SheetCounter).Name = "Report" Or Sheets(SheetCounter).Name = "LTV" Or Sheets(SheetCounter).Name = "Master List" Or Sheets(SheetCounter).Name = "Sheet1" Then
        'Do nothing for utility sheets
    Else
    'MsgBox "Now processing sheet " & Sheets(SheetCounter).Name
        Sheets(SheetCounter).Activate
        MonthAdded = ActiveSheet.Name
        Set DataRange = ActiveSheet.Range("A2", Range("A2").End(xlDown))
        RowCounter = DataRange.Rows.Count
        TxnCounter = 0
        On Error Resume Next
        
        For Each RefCell In DataRange
            If RefCell.Offset(0, 1) = "Settled Successfully" Then               'If the txn was settled successfully, generate the client key and check if exists
                UniqueKey = RefCell.Offset(0, 27) & RefCell.Offset(0, 30)       'Generate the unique customer key from billing address and zipcode
                'UniqueKey = "TEST DATA"
                
                KeyResult = IsInArray2DIndex(UniqueKey, MasterArray)
                If KeyResult(0) >= 0 And KeyResult(1) >= 0 Then
                    Debug.Print Chr(34) & MasterArray(KeyResult(0), KeyResult(1)) & Chr(34) & " exists in array at row: " & KeyResult(0) & ", col: " & KeyResult(1)
                    CalcRetained = CalcRetained + 1
                Else
                'IF THE GENERATED KEY DOES NOT EXIST IN THE MASTER LIST:
                    Debug.Print UniqueKey & " does not exist in array"
                    'ReDim Preserve MasterArray(MasterCount + 1, 2)           'Expand the existing Master key array to add in the new keys
                    MasterArray(MasterCount, 1) = UniqueKey                     'Write unique key to master list
                    MasterArray(MasterCount, 2) = MonthAdded                    'Write month added to master list
                    CalcNew = CalcNew + 1                                       'Count as new customer/household
                    Debug.Print MasterArray(MasterCount, 1) & " WAS WRITTEN TO ARRAY FOR " & MasterArray(MasterCount, 2) & " AT POSITION " & MasterCount
                End If
                
            End If
            MasterCount = MasterCount + 1
            TxnCounter = TxnCounter + 1                                 'Increment counter
            'ReDim MasterArray(MasterCount, 2)
           '[ Debug.Print MasterArray(MasterCount, 1) & " | " & MasterArray(MasterCount, 2)
            
        Next
        On Error GoTo 0
    End If
    'STORE THE CALCULATED VALUES FOR REPORTS:
    CalcArray(SheetCounter, 0) = MonthAdded
    CalcArray(SheetCounter, 1) = CalcNew
    CalcArray(SheetCounter, 2) = CalcRetained
Next Sheet


'====WRITE THE UPDATED MASTER LIST====


Worksheets("Sheet1").Activate
'OPTION A
'Set Summary = Worksheets("Sheet1").Range("A1").Resize(UBound(MasterArray, 1) + 1)
'Summary = MasterArray
For MasterCount = 1 To UBound(MasterArray, 1)
'MasterCount = RowCounter
'MsgBox MasterArray(RowCounter, 1)


'DEBUG TEST
Debug.Print "Writing to array:" & MasterArray(MasterCount, 1) & MasterArray(MasterCount, 2)


 '   Summary.Cells(RowCounter, 1).Value = MasterArray(RowCounter, 1) & "dddd"
 '   Summary.Cells(RowCounter, 2).Value = MasterArray(RowCounter, 2) & "FFFF"
 '   RowCounter = RowCounter + 1


Next




'OPTION B:
'Worksheets("Sheet1").Range("A1").Resize(UBound(MasterArray, 1) + 1, UBound(MasterArray, 2) + 1).Value = MasterArray


'MsgBox TxnCounter & " RECORDS PROCESSED!" 'Pause during testing to check values


'====WRITE CALCULATED AMOUNTS TO CELLS====
'For x = 1 To MasterCount
 '   Debug.Print MasterArray(x, 1)
'Next


Sheets("Report").Range("c7").Value = CalcArray(11, 1)
Sheets("Report").Range("c8").Value = CalcArray(10, 1)
Sheets("Report").Range("c9").Value = CalcArray(9, 1)
Sheets("Report").Range("c10").Value = CalcArray(8, 1)
Sheets("Report").Range("c11").Value = CalcArray(7, 1)
Sheets("Report").Range("c12").Value = CalcArray(6, 1)
Sheets("Report").Range("c13").Value = CalcArray(5, 1)
Sheets("Report").Range("c14").Value = CalcArray(4, 1)
Sheets("Report").Range("c15").Value = CalcArray(3, 1)
Sheets("Report").Range("c16").Value = CalcArray(2, 1)


'====CLEAN UP====
'RESTORE APPLICATION STATE
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
'====CLEAN UP COMPLETED====
Worksheets("Sheet1").Activate
End Sub

Public Function IsInArray(MasterArray As Variant, UniqueKey As String) As Boolean
    Dim i As Integer, found As Boolean
    found = False


    If Not Len(Join(MasterArray)) > 0 Then
        found = False
    Else
        For i = 0 To UBound(MasterArray)
            If MasterArray(i) = UniqueKey Then
               found = True
            End If
        Next i
    End If
    IsInArray = found
End Function
 
Hello @Fluff!

Apologies if this is like the return of a bad nightmare, but I hope you'll be able to give me some more advice on this project if I haven't frustrated you enough yet! :laugh:

Everything you have helped me with so far works beautifully. However, I also have to segregate unique clients/households by the number and value of the orders they have placed over several months. So for example, I need to count how many households placed only 1 order and sum the value of those orders. Then count how many households placed 2 orders, and sum the value of those orders and so on an so forth until households who placed 25 orders or more.

I have done some thinking and it seems to me as if I need to create an array containing variables to store the number of unique households that have placed 1 order, 2 orders, 3 orders, up to 25 orders and the values of those orders for each instance. I have no idea how to count and store how many households place x number of orders though. Would it work to write the value 1 to for each unique household ID to an array when they first order and then having to search the array for that ID when it next occurs in a transaction, then adding +1 to that record or am I oversimplifying/overcomplicating this?

Or should I rather use the same Master array that counts unique households and just add additional dimensions for number of orders and orders value for that Household ID and then run a calculation on that array to determine how many households ordered 1, 2 or x times?

One caveat: I have had to adapt the Dictionary references as the code has to run on Excel for Mac which does not provide for Dictionary. Here is where I am now (Again, please overlook my messy code and random commenting!):

Code:
Option Base 0

Sub BeemerangNew()


   Dim Ws As Worksheet
   Dim MasterArray As Variant, NewList As Variant, RetainedList As Variant, ShtAry As Variant
   Dim CustArray As Variant, x As Variant, MRRArray As Variant
   Dim i As Long
   Dim Dic As Dictionary, Dic2 As Dictionary
   Dim RefCell As Range
   Dim UniqueKey As String
   Dim ListCounter As Long
   
   Set Dic = New Dictionary
   Set Dic2 = New Dictionary
   
   Application.Calculation = xlCalculationManual
   
   With Sheets("Master List")
      .Range("A1").CurrentRegion.Offset(2, 1).ClearContents
      CustArray = .Range("A1").CurrentRegion.Value2
      '.Range("A1").CurrentRegion.Select
      .Range("A16").CurrentRegion.Offset(2, 1).ClearContents
      MRRArray = .Range("A16").CurrentRegion.Value2
      '.Range("A16").CurrentRegion.Select
   End With
   
   ReDim NewList(2, ListCounter)
   ReDim RetainedList(2, ListCounter)
   Dim RetainPlacer As Long
   RetainPlacer = 1
   
   For i = 3 To UBound(CustArray, 2)
      If Evaluate("isref('" & Format(CustArray(2, i), "mmm yyyy") & "'!A1)") Then
         Set Ws = Sheets(Format(CustArray(2, i), "mmm yyyy"))
         'If RetainPlacer = 0 Then
         'RetainPlacer = 1
         'Else
         'RetainPlacer = RetainPlacer + 1
         '   End If
         Ws.Activate
         For Each RefCell In Ws.Range("A2", Ws.Range("A" & Rows.Count).End(xlUp))
            RefCell.Activate
            If RefCell.Offset(0, 1).Value = "Settled Successfully" Then
               UniqueKey = WorksheetFunction.Proper(RefCell.Offset(, 27).Value) & "|" & RefCell.Offset(, 30).Value
               If Not Dic.Exists(UniqueKey) Then
                Dic.Add UniqueKey, i
                 CustArray(i, 2) = CustArray(i, 2) + 1
                 'MRRArray(i, 2) = MRRArray(i, 2) + RefCell.Offset(i - 3, 2).Value My code
                 
                 MRRArray(i, 2) = MRRArray(i, 2) + RefCell.Offset(, 2).Value
                 
                 RefCell.Interior.ColorIndex = 5
                 ReDim Preserve NewList(2, ListCounter)
                 
                 NewList(1, ListCounter) = UniqueKey
                 NewList(2, ListCounter) = Ws.Name
                 'Debug.Print UniqueKey & " first purchased in " & NewList(2, ListCounter)
                 'If ListCounter = 0 Then ListCounter = 1
                 
                 Worksheets("Dic").Cells(ListCounter + 1, 1).Value = NewList(2, ListCounter)
                 Worksheets("Dic").Cells(ListCounter + 1, 2).Value = NewList(1, ListCounter)
                 Worksheets("Dic").Cells(ListCounter + 1, 3).Value = RefCell.Offset(, 2).Value
                 ListCounter = ListCounter + 1
               ElseIf Not Dic2.Exists(UniqueKey) Then
                  Dic2.Add UniqueKey, RefCell.Offset(i - 3, 2).Value
                  x = Dic.Item(UniqueKey)
                  CustArray(x, i) = CustArray(x, i) + 1
                  'MRRArray(x, i) = MRRArray(x, i) + RefCell.Offset(i - 3, 2).Value
                  
                  MRRArray(x, i) = MRRArray(x, i) + RefCell.Offset(, 2).Value
                  
                  RefCell.Interior.ColorIndex = 45
                  ReDim Preserve RetainedList(2, ListCounter)
                  RetainedList(1, ListCounter) = UniqueKey
                  RetainedList(2, ListCounter) = Ws.Name
                  'Debug.Print RetainedList(1, ListCounter) & " purchased again in " & RetainedList(2, ListCounter)
                  Worksheets("Dic").Cells(RetainPlacer, 5).Value = RetainedList(2, ListCounter)
                  Worksheets("Dic").Cells(RetainPlacer, 6).Value = RetainedList(1, ListCounter)
                  Worksheets("Dic").Cells(RetainPlacer, 7).Value = RefCell.Offset(, 2).Value
                  RetainPlacer = RetainPlacer + 1
            ElseIf Dic2.Exists(UniqueKey) Then
                RefCell.Interior.ColorIndex = 45
                MRRArray(x, i) = MRRArray(x, i) + RefCell.Offset(, 2).Value
               End If
            End If
         Next RefCell
      End If
      Dic2.RemoveAll
      'MsgBox ActiveSheet.Name & " has " & ListCounter & " new customers!"
   Next i
   Sheets("Master List").Range("A1").Resize(12, UBound(CustArray, 2)).Value = CustArray
   Sheets("Master List").Range("A16").Resize(12, UBound(MRRArray, 2)).Value = MRRArray
   
   'ActiveWorkbook.Worksheets("Test").Range("A2:B" & ValidRow + 1) = Application.Transpose(Data) 'swap rows and cols back
   
   Sheets("Master List").Range("v2").Resize(ListCounter, 3).Value = Application.Transpose(NewList)
   'Sheets("Master List").Range("A32").Resize(12, UBound(NewList, 2)).Value = NewList
   'Sheets("Master List").Range("G32").Resize(12, UBound(RetainedList, 2)).Value = Application.Transpose(RetainedList)
   'Stop
   Sheets("Master List").Activate
   Application.Calculation = xlCalculationAutomatic
   
End Sub
 
Upvote 0

Excel Facts

Copy PDF to Excel
Select data in PDF. Paste to Microsoft Word. Copy from Word and paste to Excel.
As this needs to work on a Mac, you'd better start a new thread, as I have no knowledge of Macs.
 
Upvote 0

Forum statistics

Threads
1,224,743
Messages
6,180,687
Members
452,994
Latest member
Janick

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top