Dim a(10) as string
Dim b(10) as string
Dim c(10) as string
Dim d(10) as String
d= Array(a,b,c)
This isn't working.
You were very close in your example. All you need to do is to declare "d" as Variant and not as String-array, because it isnt:
Private Sub arraytest()
Dim a(10) As String
Dim b(10) As String
Dim c(10) As String
a(0) = "test"
Dim arrD As Variant 'Dimensionless variable to hold the result of "Array-Function"
arrD = Array(a, b, c)
Debug.Print arrD(0)(0)
End Sub
Think of "Array" as a function building an Array-Object with all the correct dimensions and properties. All you need is something to hold that (a Variant), whatever it really becomes.
Note that contrary to normal multi-dimensional arrays, you access the values via (x)(y) and not (x,y).
Related
'Declare variables for cell values attained from APR spreadsheet
Dim orgSheetvalues(0) As String 'Project Title
Dim orgSheetvalues(1) As String 'Circuit Tag
Dim orgSheetvalues(2) As String 'District
Dim orgSheetvalues(3) As String 'State
Dim orgSheetvalues(4) As Date 'Date recieved
Dim orgSheetvalues(5) As Currency 'Planned Capital Cost
Dim orgSheetvalues(6) As Currency 'Actual Capital Cost
Dim orgSheetvalues(7) As Date 'Capital work completed date
Dim orgSheetvalues(8) As Currency 'Planned O&M Cost
Dim orgSheetvalues(9) As Currency 'Actual O&M Cost
Dim orgSheetvalues(10) As Date 'O&M work completed date
Dim orgSheetvalues(11) As String 'RWP File Path
Clearly, this does not work. Does anyone know of a way I can use the same variable name, for different variable types, in a way that can be iterated as the above would if it worked (eg. orgSheetvalue(iterating variable))?
While the Variant array will work just fine, it's prone to errors as you will need to remember the datatype each position holds.
A custom Type in my opinion would be better approach.
Public Type MyCustomType
ProjectTitle As String
CircuitTag As String
District As String
State As String
DateRecieved As Date
PlannedCapitalCost As Currency
'...
End Type
Sub T()
Dim o As MyCustomType
o.ProjectTitle = "abc"
o.CircuitTag = "..."
o.DateRecieved = Date
End Sub
example
Option Explicit
Sub aaa()
Dim bbb(10) As Variant
bbb(0) = "test 123" ' string
Set bbb(1) = Range("a1") ' object
bbb(2) = 98765 ' numeric
Debug.Print bbb(0); vbTab; bbb(1).Interior.Color; vbTab; bbb(2)
End Sub
Needed code is something like this:
Dim myArray(0) As String
Dim ay As String = "ay"
myArr & ay(0) = "asd"
I've tried but did not worked
Dim classlist1(0) As String
Dim classlist2(0) As String
Dim classlist3(0) As String
Dim classlist4(0) As String
Dim count As Integer = 0
For _year As Integer = 1 To 4
("classlist" & _year)(count) = "hi"
count += 1
Next
Any time you see something like this:
Dim classlist1(0) As String
Dim classlist2(0) As String
Dim classlist3(0) As String
' etc.
It's an indication that you're using the wrong data structure. Instead of trying to dynamically build variable names (which isn't really possible in a static language, at least not without some really ugly reflection code with a high potential for runtime errors), just use a collection.
For example, if you want a collection of strings:
Dim classList As New List(Of String)()
And if you want a collection of collections of strings:
Dim classLists As New List(Of List(Of String))()
Then you can reference the nested lists within the parent list. So to add your first "year" of classes:
classLists.Add(new List(Of String))
And add a class to that year:
classLists(0).Add("some value")
As you can see, it starts to get a little difficult to keep track of the data structures. This is where creating custom types and structures becomes very useful. For example, rather than representing a "year" as a list of strings, create an actual Year class. That class can internally hold a list of strings, and other logic/data.
Try Dictionary<TKey, TValue> Class From MSDN.
Dim classLists As New Dictionary(Of String, String)()
'Add items with keys
For _year As Integer = 1 To 4
classLists.Add(String.Format("classlist{0}",_year), "hi")
Next
And you can get value by key later
Dim key As String = "classlist2"
Dim value As String = classLists(key)
Got a simple question. The Array() function in VBA does return a two dimensional array? I'm trying to create a one dimensional array with this function and use it in the filter() function but it says "type mismatch". And if that's the case, how can I force Array() to create a one dimensional array?
Sub tester()
Dim xWorkb As Excel.Workbook
Dim xFiles_target() As String
Dim file_path As String
xFiles_target = Array("Bella.xls", "Fizz.xls", "Milo.xls")
file_path = Dir("C:\Users\hans\Desktop\")
Do While Len(file_path) > 0
Debug.Print file_path
If UBound(Filter(xFiles_target, file_path)) >= 0 Then
Debug.Print "found " & file_path
End If
file_path = Dir
Loop
End Sub
Array function does create a 1D Array. However the function requires the variable you are assigning to, to be of Variant type. It cannot be String/Number.
Dim tmpArr() As String
tmpArr = Array("Hello", "World")
The above is likely to throw Type mismatch error. However,
Dim tmpArr()
tmpArr = Array("Hello", "World")
The above will take it as such. That is no error will be thrown but the tmpArray now has two elements to it.
The Split function will result in a String array. Although Variant type can take in String, a Number array cannot take in the Split function.
More information about this neatly organized here : http://patorjk.com/programming/tutorials/vbarrays.htm
Hope this helps.
I have a data struct for a piece of lumber. I've built a class to handle dimensions (architectural, metric, etc... ) that I'd like to make the data type of the length member of this struct. VB says I can't use 'new' in my definition unless I make the member 'Shared'. If I make the member 'Shared' I can't see the data when I try to access the member in my code.
Public Structure PieceInfo
Dim ProjectNumber As String
Dim ProjectName As String
Dim BuildingType As String
Dim BuildingNumber As String
Dim BLevel As String
Dim Batch As String
Dim Trussname As String
Dim Span As Single
Dim PieceName As String
Dim LumberType As String
Shared PieceLength As New clsDimension
Shared StockLength As New clsDimension
Dim LeftSplicePlate As String
Dim RightSplicePlate As String
End Structure
How can I use my "clsDimension" object as the data type for the "Length" members of my struct?
As all the comments indicate: You should change your Struct to a class because you want to reference it. And due to Structs being value types and Classes being reference types, This is what you want:
Public Class PieceInfo
Dim ProjectNumber As String
Dim ProjectName As String
Dim BuildingType As String
Dim BuildingNumber As String
Dim BLevel As String
Dim Batch As String
Dim Trussname As String
Dim Span As Single
Dim PieceName As String
Dim LumberType As String
Shared PieceLength As New clsDimension
Shared StockLength As New clsDimension
Dim LeftSplicePlate As String
Dim RightSplicePlate As String
End Class
.NET Structure don't have default constructor, you'll have to create your own (or a function to initialize the values). But that kind of defeat the purpose of the struct.
Public Structure PieceInfo
Dim ProjectNumber As String
Dim ProjectName As String
Dim BuildingType As String
Dim BuildingNumber As String
Dim BLevel As String
Dim Batch As String
Dim Trussname As String
Dim Span As Single
Dim PieceName As String
Dim LumberType As String
Dim PieceLength As clsDimension
Dim StockLength As clsDimension
Dim LeftSplicePlate As String
Dim RightSplicePlate As String
Public Sub New(ByVal t As String)
PieceLength = New clsDimension
StockLength = New clsDimension
End Sub
End Structure
But like others said, changing it to a class is the right thing to do. Class is reference type and structure is value type.
I am using the following structure many times throughout my code to pass a set of data to a function:
Public Structure MyStruct
Dim ResourceID As String
Dim RSRCName As String
Dim CommercialType As String
Dim ParticipantName As String
Dim ASReserveZone As String
Dim SCADAStatusQuality As String
Dim SCADAStatus As String
Dim SCADAMWQuality As String
Dim ManualDispatchReason As String
Dim RegUpQual As Boolean
Dim RegDownQual As Boolean
Dim SuppQual As Boolean
Dim SpinQual As Boolean
Dim UseEmergencyLimits As Boolean
Dim FollowLastDispatch As Boolean
Dim ASOfferCurveDict As HybridDictionary
Dim XIC As Integer
Dim PriceBased As Integer
Dim PNodeID As Integer
Dim Committed As Integer
Dim CommitmentStatus As Integer
Dim ManualDispatch As Integer
Dim LastApprdNumOfIntervalsToMax As Integer
Dim MWCurve() As Double
Dim EnergyOfferCurve() As Double
Dim PlannedMW As Double
Dim SCADAMW As Double
Dim InitialOnHours As Double
Dim LastApprdDispatchMW As Double
Dim TotalRampedCRDeployMW As Double
End Structure
Dim Struct as MyStruct
I can use Struct = Nothing to reset the data, but I would rather iterate through the structure and set all the numeric values to 999999999. Any idea how to do this?
You could do it with reflection, but I wouldn't necessarily recommend it. I'd sooner just add a Clear or Reset method to the structure which sets all the values to their default values. Another option would be to set the default values when the fields are declared:
Public Structure MyStruct
' ...
Dim XIC As Integer = 999999999
Dim PriceBased As Integer = 999999999
Dim PNodeID As Integer = 999999999
' ...
End Structure
Then, to reset a variable to all the default values, just do this:
myVariable = New MyStruct()
I should also mention, unless it really needs to be a structure for some reason, you should change this to a class. It's quite a lot of data to be passing around on the stack all the time.