Passing a '2 dimensional array' local variable to a class level variable - arrays

I have a sub which reads an Excel file (X rows by 5 columns) and make a copy of its data into a String array called 'matrix' in VB.NET. I do need, however, to access of this array in some other subs as well. I was hoping to pass the array to a class level array variable and then retrieve info from that one instead. But I don't how to achieve this goal.
Public Sub ReadFromExcel()
Dim excel As Application = New Application
Try
Dim wrkbook As Workbook = excel.Workbooks.Open(IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.Location) & _
"EXCELFILE.xls")
Dim sheet As Worksheet = wrkbook.Sheets(1)
Dim cell As Range = sheet.UsedRange
Dim LastRow As Long = 0
sheet.Activate()
With sheet
LastRow = .Cells(.Rows.Count, 1).End(XlDirection.xlUp).Row
End With
Dim matrix(LastRow - 1, 4) As String
For i As Integer = 2 To LastRow
For j As Integer = 1 To 5
matrix(i - 1, j - 1) = cell(i, j).VALUE
Next
Next (i)
wrkbook.Close()
excel.Quit()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

You might try this:
Public Class Sample
Private xlsFileContents(0,0) as String
Public Sub ReadFromExel()
Dim excel As Application = New Application
Try
'all of your code here up to "excel.quit"
'now redim the class array to match your matrix array
'<array>.GetUpperBound gets the integer value of the highest index in that dimension of your array.
'It accepts a zero-bound integer to determine which dimension you are referring to.
ReDim xlsFileContents(matrix.GetUpperBound(0), matrix.GetUpperBound(1))
xlsFileContents = matrix
Catch
'your code here
End Try
End Class
I tried this in a simple console application where I manually entered data into the matrix array, and it worked for me.

Related

Using arrays in a loop

Each page (01,02...11,12) represents a month of the year.
Each page has different staff and salaries. I want to see the workers data on these pages in one page. While doing this, I need to do some operations. Since it would be slow in terms of speed, I wanted to do the operations inside the arrays instead of copying this data to a page and performing the operations there.
What I actually want to do and learn.
We can navigate pages one by one in a loop. I want to do the same for arrays (1st array, 2nd array, ... 11 array, 12 array).
Option Explicit
Option Base 1
Dim d1() As Variant, d2() As Variant, d3() As Variant, d4() As Variant, d5() As Variant, d6() As Variant
Dim d7() As Variant, d8() As Variant, d9() As Variant, d10() As Variant, d11() As Variant, d12() As Variant
Dim personel As Collection, sonuc() As Variant, d() As Variant
Sub Example()
Dim i As Integer
For i = 1 To Worksheets.Count
Debug.Print Worksheets(i).Name
Next i
End Sub
Sub Example2()
Dim i As Integer
For i = 1 To 12
' ???? d & i = Worksheets(i).Range("A1:AA34")
Next i
End Sub
I recommend creating a 2 dimensional array of data where each elemnt holds the information for a single worksheet.
Creating an Employee class would make the life easier in the long run. WatchClass Modules Explained in Simple English (with examples)
Sub Main()
Dim Data As Variant
Data = AllWorkSheetData
Stop
End Sub
Function AllWorkSheetData() As Variant()
Dim Result As Variant
ReDim Result(1 To Worksheets.Count)
Dim i As Long
For i = 1 To Worksheets.Count
Result(i) = Worksheets(i).Range("A1:AA34")
Next i
AllWorkSheetData = Result
End Function
Do you need 12 different arrays for your operation?
If you want to paste the data one after the other on a single sheet, you can use a single array and reassign values in each iteration.
Dim d() As Variant, i As Integer
For i = 1 to Worksheets.Count
d = Worksheets(i).Range("A1:AA34").Value2
'Do your calculations with d array.
'
'
'
'Paste d array in aggregate sheet.
Next i
Also, use Excel object datatypes along with For Each loop instead of integers. It is much better to understand.
Dim ws As Worksheet
Dim d() As Variant
For Each ws In Worksheets
d = ws.Range("A1:AA34").Value2
'Do your calculations with d array.
'
'
'
'Paste d array in aggregate sheet.
Next ws
You need to create an array to hold variants that you are connecting on to the data from your sheet:
Dim d(1 To 12) As Variant
Dim i As Integer
For i = 1 To 12
d(i) = Worksheets(i).Range("A1:AA34")
Debug.Print d(i)(1, 1) ' access one the value from one cell of the sheet that has been read into the array.
Next i
End Sub

Populating ListBox in Userform with each element of an array

I have the following problem: In one module I created an array "arArray" with values from a specific column. Each value of said array represents a weeknumber based on another dataset. The array is defined in another module as Public under Option Explicit. This works perfectly. Below the code for the array.
Dim arrayData As Range
Dim sh As Worksheet
Dim Row_Count As Integer
Dim i As Integer
Dim lastRow2 As Long
Set sh = ThisWorkbook.Sheets("Import")
lastRow2 = sh.Columns(45).Find("*", , , , xlByRows, xlPrevious).Row
Set arrayData = sh.Range("AS2:AS" & lastRow2)
arArray = sh.Range("AS2:AS" & lastRow2)
Row_Count = arrayData.Rows.Count
For i = 1 To Row_Count
arArray(i, 45) = Cells(i, 45).Value
Next i
Now I'm trying to fill all values of "arArray" into the Listbox "Lst_Tabellen" of the UserForm "Auswertung". Below the code for Initialization:
Public Sub UserForm_Initialize()
With Lst_Tabellen
Lst_Tabellen.Clear
Lst_Tabellen = arArray
End With
End Sub
I'm calling this userform in another sub:
Public Sub Call_Userform()
Auswertung.Show
End Sub
My problem is, that the Userform opens, but without any values. I never programmed a userform before, so I'm really stuck here. Can you guys see my error?

Populate a one-dimensional array with values from an Excel Table column using VBA

The code below is meant to read columns from an Excel table into arrays, which can then be used to determine whether each "Project" belongs to the Environment "Group", and if so, to add the project number and dollar value to another array. I am having some issues with my code, and have been searching the internet and StackOverflow but have been able to find very little information on dealing with Excel Tables using VBA. I am using Excel 2010.
Sub UpdateProjectsAndCharges()
'Define arrays to be used
Dim projectArray() As Variant
Dim uniqueProjectArray(100) As Variant
Dim dollarValue() As Variant
Dim envProjectArray(100) As Variant
Dim envDollarValue(100) As Double
Dim cumulativeCosts(100) As Double
'Define all tables in this sheet as list objects
Dim UnitsValues As ListObject
Dim ChargingTracking As ListObject
'Define counters to be used
Dim counter As Integer
Dim counter2 As Integer
'Set variables for each table in sheet
Set UnitsValues = Sheets("Cluster Data").ListObjects("UnitsValues")
Set ChargingTracking = Sheets("Cluster Data").ListObjects("ChargingTracking")
'Find last row in table
With Sheets("Cluster Data")
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
End With
'Define variables to be used in loops
Dim userGroup As Variant
Dim project As Variant
Dim Value As Variant
'Set arrays to respective columns from UnitsValues table
userGroups = Range("UnitsValues[Group]")
projectArray = Range("UnitsValues[Project]")
dollarValue = Range("UnitsValues[Dollar Value]")
'Redefine length of arrays to number of rows in table
ReDim Preserve projectArray(lastRow)
ReDim Preserve dollarValue(lastRow)
'Set counter values
counter = 1
counter2 = 1
For Each userGroup In userGroups
project = projectArray(counter)
Value = dollarValue(counter)
If userGroup = "Environment" Then
envProjectArray(counter2) = project
envDollarValue(counter2) = Value
counter2 = counter2 + 1
MsgBox ((envProjectArray(counter2) & " " & envDollarValue(counter2)))
End If
counter = counter + 1
Next userGroup
I was receiving the "Subscript out of range" error with these lines:
project = projectArray(counter)
Value = dollarValue(counter)
I looked up the error and thought that these lines would perhaps fix the problem:
ReDim Preserve projectArray(lastRow)
ReDim Preserve dollarValue(lastRow)
Now, I am receiving the same error on the lines above instead, and have run out of ideas on how to fix the error. I suspect it is happening because I assigned a range into an array, but I'm not certain.
Change:
project = projectArray(counter)
Value = dollarValue(counter)
to
project = projectArray(counter, 1)
Value = dollarValue(counter, 1)
Arrays read from worksheets always are multidimensional even if you just have 1 column.
In this case you are specifying that column to be 1, every time.

VBA Count Values in Array

I've read the post on this VBA problem, but my VBA script is still not working.
Public Sub Test()
Dim arrNames As Variant 'Declare array named "arrNames"
arrNames = Sheet1.Range("F2:F1000") 'Array filled with column F
intN = Application.CountIf(arrNames, "*") 'does not work intent: count cells w/info
'intN = Application.CountA(arrNames) 'works but MsgBox displays value of 999
MsgBox (intN)
End Sub
How do I get the number of cells in my array containing any value?
EDITED version after help
Public Sub Test()
Dim arrNames As Variant 'Declare array named "arrNames"
Dim i As Long
arrNames = Sheet1.Range("F2:F1000") 'Array filled with column F
For i = LBound(arrNames) To UBound(arrNames)
If (arrNames(i,1) = "") Then
EmptyCounter = EmptyCounter + 1
End If
Next i
End Sub
There is no direct way to do it, as far as I understand. But you could run a simple loop to check if the values are equal to "" assuming string data.
For e.g.
For i = LBound(ArrayName) to UBound(ArrayName)
If (ArrayName(i) = "") Then
EmptyCounter = EmptyCounter + 1
End If
Next i
If it's numeric or other type of data, you may try variations of the above loop using functions such as IsEmpty(VariableName) etc.
You can try this:
intN = Worksheets("Sheet1").Range("F2:F1000").Cells.SpecialCells(xlCellTypeConstants).Count
MsgBox intN
100% it works.

How to assign excel cell with string to array value in visual basic?

I'm pretty new to visual basic, but I'm having trouble assigning cell values to members of an array. Basically what I am doing is looping through a column and assigning each cell to a new part of the array. Test code is posted below:
Sub Test()
Dim List(5) As String
Dim celltext As String
For i = 1 To 5
celltxt = ActiveSheet.Range("K" & i).Text
List(i) = celltext
MsgBox List(i)
Next i
End Sub
Each time the message box pops up though, it is blank, meaning that the assignment didn't work. The cells at those coordinates DO have values. Any clues?
You are assigning to "celltxt" but reading from "celltext".
Add Option Explicit at the top of every module -- that will make these types of errors more obvious.
When you Dim List(5) As String. The lowest element in the array is 0 and not 1. You might want to change that to Dim List(1 to 5) As String else your first element will always be blank in the array.
You are using ActiveSheet. Are you sure it is the right sheet?
Try this code
Sub Test()
Dim List(1 To 5) As String
Dim ws As Worksheet
Dim i as Long
Set ws = ThisWorkbook.Sheets("Sheet1")
For i = 1 To 5
List(i) = ws.Range("K" & i).Value
MsgBox List(i)
Next i
End Sub
You might also with to try:
Dim List As Variant
Dim i As Long
List = ActiveSheet.Range("K1:K5")
For i = 1 To UBound(List)
MsgBox List(i, 1)
Next i
This will add performance by only reading from the worksheet once instead of each time the loop is looped.

Resources