I am creating a macro that counts how many hours I have assigned to a job over a period of a month. I have the code for the list of jobs and time spent on each job working, which saves each job name and the related hours in the array JobHours(i,j). Once I try and access this array in the userform it is not available.
My code in the module
Option Explicit
Public JobHours() As Variant
Sub MonthlyHoursShow()
Monthly_Hours.Show
End Sub
Sub MonthlyHours(SelMonth As Variant)
'Code which assigns values to JobHours() -
ReDim JobHours(1, 0)
JobHours(0, 0) = "Job Number"
JobHours(1, 0) = "Hours"
'There are a few loops to determine what values to collect, and they are then
'assigned to JobHours() as follows:
cValue = UCase(ws.Cells(j, 2).Text)
ReDim Preserve JobHours(1, JobNum)
JobHours(0, JobNum) = cValue
JobHours(1, JobNum) = ws.Cells(j, 27).Value
Worksheets("25 Mar").Cells(8 + JobNum, 30).Value = JobHours(0, JobNum)
Worksheets("25 Mar").Cells(8 + JobNum, 31).Value = JobHours(1, JobNum)
'where JobNum is a counter for the number of jobs, and is incremented as part of the loop.
Debug.Print "Upper Bound of JobHours() = " & UBound(JobHours, 2) - 'Returns as 38
Debug.Print "Total Number of jobs is " & Application.CountA(JobHours) - 'returns as 78
End Sub
and in my userform:
Private Sub CalcButton_Click()
SelMonth = MonthBox.Value
Call MonthlyHours(SelMonth)
'Debug.Print "Upper Bound of JobHours() = " & UBound(JobHours, 2) - 'Returns error
Debug.Print "Total Number of jobs is " & Application.CountA(JobHours) - 'Returns as 1
End Sub
If I don't comment the UBound command in the first Debug.Print line the I get the following error:
Compile Error: Expected Array
My understanding was that if the Array was declared as a public variable it will pass to a userform - In fact I had this working! I then saved the workbook, closed it and reopened and now have the problem??
I have no idea why this isn't working - it is my first real attempt at using an array. If you have any ideas they would be greatly appreciated.
Thanks, Dan
JobHours? Where isuboundbeing used?ReDimstatement) before acceding to it (like when you try to get its bounds). Besides when you exit the macro, you lose all variable values, be theyPublicor not. If you want to keep variables values from one macro session to another, you have to store them (maybe in a sheet, or in a txt file) and then retrieve themJobHourssomewhere else as a routine/module name.JobHours()is dimensioned and assigned values. I have also added the uBound line to the module code, as well as the form code, to show the different values they return.JobHourswhich was causing the problem. All fields in the userform are now labelled `Job_Hours' and it is all working :) Thanks!