VBA Adding a class to a collection [duplicate] - vba

This question already has answers here:
VB6 pass by value and pass by reference
(2 answers)
Closed 1 year ago.
I have a class module called Holding. In it are several public variables. My code is this:
Dim holdings as Collection
Dim h as Holding
Set holdings = new Collection
For i = 1 to last
Set h = new Holding
h.x = y
'... etc
holdings.Add(h)
Next i
This gives me error "object doesnt support this property or method" on the holdings.Add(h) line, but everywhere I look, it gives this exact example of how to achieve this. What am I missing?

Remove the parentheses.
holdings.Add h
Otherwise you are trying to add to the collection the value of the default property of your Holding instance, and it doesn't have a default property.

Related

Object required when retrieving value from InputBox [duplicate]

This question already has answers here:
Object Required Error When Declaring String Variable
(1 answer)
VBA Excel "Compile error: Object Required"
(2 answers)
Closed 1 year ago.
Hey guys I have a a coding issue in vba.
Dim table As String
Set table = InputBox("Text","Title","Default")
I then get the message:
Error while compiling
Object required
The phrase
table =
Is marked blue
Why do I get the error while compiling?
If InputBox does return a String you have to remove the Set (which is only needed for objects):
Dim table As String
table = InputBox("Text","Title","Default")
The Set statement is used with variables that are an Object type.
Per the VBE Glossary for object-type;
A type of object exposed by an application through Automation, for example, Application, File, Range, and Sheet. Use the Object Browser or refer to the application's documentation for a complete listing of available objects.
A String is not an object data type so you don't need to include the Set keyword.

Why doesn't a String of Nothing cause cause an exception? (BC42104) [duplicate]

This question already has answers here:
Difference between Equals/equals and == operator?
(11 answers)
Closed 3 years ago.
If I declare a string but do not assign a value, the Equals function throws an exception but it doesn't throw an exception if it is compared to a value.
The error list warns about the problem:
Warning BC42104 Variable a is used before it has been assigned a
value. A null reference exception could result at runtime.
Dim a As String
Dim b as string = "bar"
a.Equals("foo") 'causes System.NullReferenceException
a = "foo" 'No exception although a is nothing
a = b 'No exception although a is nothing
I know the warning says it COULD cause an exception, but does anyone know why this is the happening?
This is because Dim a As String declares the type of variable a but doesn't assign anything to it. This is basically saying : "This variable was made to hold a String object, but it doesn't hold any right now". On the other hand, Dim b As String = "bar" declares the variable and its type, but also assigns a String object to it ("bar"). The reason a.Equals("foo") returns an exception is because you only declared it without assigning anything to it (so you are trying to access an object that isn't there). a = "foo" works because you are assigning a String object of value "foo" to the variable a. It's like saying : "This variable now holds a String object with value 'foo'".
Edit :
While your code points to the assignment of the variable a, I was made aware that you wanted to know why the = operator, as a comparison operator, works. This is because what I said earlier isn't entirely true when I said it didn't hold an object. It actually is of Nothing value (which sets it as a null reference) if no String object was assigned to it (String is a nullable object).
See : https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/nothing
Hope this helps.

Object variable or With Block variable not set error when accessing members of BuildingBlockEntries collection

I am attemping to access members of a template's BuildingBlockEntries collection through a macro in Microsoft Word 2007. As it is a collection, I first thought a For Each loop would be the best way to to this:
For Each bBlock In NormalTemplate.BuildingBlockEntries
MessageBox.Show (bBlock.Name)
Next bBlock
However this attempt through the error: Object doesn't support property or method.
So I tried this method which was suggested here:
Templates.LoadBuildingBlocks
Dim iBB As Integer
iBB = NormalTemplate.BuildingBlockEntries.Count()
Dim bb As Word.BuildingBlock
Dim i As Integer
Dim objCounter As Object
If iBB > 0 Then
For i = 1 To iBB
objCounter = i
bb = NormalTemplate.BuildingBlockEntries.Item(objCounter)
MessageBox.Show (bb.Name)
Next
End If
However, this is resulting in the error shown in the title: Object variable or With Block variable not set.
I have tried just using an integer variable for the index, i specifically, but with now avail. How can I acheive the desired effect? What is wrong with my attempt?
Thank you for the help.
With your 2nd question the answer is that you need to use Set, as bb is an object:
Set bb = NormalTemplate.BuildingBlockEntries.Item(objCounter)
For more info on Set take a look at this SO question.
With your For/Next loop, it's not clear how you've declared bBlock. I guess it should be something like:
Dim bBlock as BuildingBlock
And perhaps the For line should reference BuildingBlocks instead of BuildingBlockEntries:
For Each bBlock In NormalTemplate.BuildingBlocks
I don't know for sure though, as I'm just looking at what pops up in Intellisense.

Dynamically create variables in VB.NET

I have been trying to figure this out for some time now and can't seem to figure out an answer to it. I don't see why this would be impossible. I am coding in VB.NET.
Here is my problem:
I need to dynamically create variables and be able to reference them later on in the code.
More Details:
The number of variables comes from some math run against user defined values. In this specific case I would like to just create integers, although I foresee down the road needing to be able to do this with any type of variable. It seems that my biggest problem is being able to name them in a unique way so that I would be able to reference them later on.
Simple Example:
Let's say I have a value of 10, of which I need to make variables for. I would like to run a loop to create these 10 integers. Later on in the code I will be referencing these 10 integers.
It seems simple to me, and yet I can't figure it out. Any help would be greatly appreciated. Thanks in advance.
The best way to do something like this is with the Dictionary(T) class. It is generic, so you can use it to store any type of objects. It allows you to easily store and retrieve code/value pairs. In your case, the "key" would be the variable name and the "value" would be the variable value. So for instance:
Dim variables As New Dictionary(Of String, Integer)()
variables("MyDynamicVariable") = 10 ' Set the value of the "variable"
Dim value As Integer = variables("MyDynamicVariable") ' Retrieve the value of the variable
You want to use a List
Dim Numbers As New List(Of Integer)
For i As Integer = 0 To 9
Numbers.Add(0)
Next
The idea of creating a bunch of named variables on the fly is not something you are likely to see in any VB.Net program. If you have multiple items, you just store them in a list, array, or some other type of collection.
'Dim an Array
Dim xCount as Integer
Dim myVar(xCount) as String
AddButton Event . . .
xCount += 1
myVar(xCount) = "String Value"
'You will have to keep Track of what xCount Value is equal to to use.
'Typically could be an ID in A DataTable, with a string Meaning

object reference not set to an instance of object [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 2 years ago.
I have been getting an error in VB .Net
object reference not set to an instance of object.
Can you tell me what are the causes of this error ?
The object has not been initialized before use.
At the top of your code file type:
Option Strict On
Option Explicit On
Let's deconstruct the error message.
"object reference" means a variable you used in your code which referenced an object. The object variable could have been declared by you the or it you might just be using a variable declared inside another object.
"instance of object" Means that the object is blank (or in VB speak, "Nothing"). When you are dealing with object variables, you have to create an instance of that object before referencing it.
"not set to an " means that you tried to access an object, but there was nothing inside of it for the computer to access.
If you create a variable like
Dim aPerson as PersonClass
All you have done was tell the compiler that aPerson will represent a person, but not what person.
You can create a blank copy of the object by using the "New" keyword. For example
Dim aPerson as New PersonClass
If you want to be able to test to see if the object is "nothing" by
If aPerson Is Nothing Then
aPerson = New PersonClass
End If
Hope that helps!
sef,
If the problem is with Database return results, I presume it is in this scenario:
dsData = getSQLData(conn,sql, blah,blah....)
dt = dsData.Tables(0) 'Perhaps the obj ref not set is occurring here
To fix that:
dsData = getSQLData(conn,sql, blah,blah....)
If dsData.Tables.Count = 0 Then Exit Sub
dt = dsData.Tables(0) 'Perhaps the obj ref not set is occurring here
edit: added code formatting tags ...
In general, under the .NET runtime, such a thing happens whenever a variable that's unassigned or assigned the value Nothing (in VB.Net, null in C#) is dereferenced.
Option Strict On and Option Explicit On will help detect instances where this may occur, but it's possible to get a null/Nothing from another function call:
Dim someString As String = someFunctionReturningString();
If ( someString Is Nothing ) Then
Sysm.Console.WriteLine(someString.Length); // will throw the NullReferenceException
End If
and the NullReferenceException is the source of the "object reference not set to an instance of an object".
And if you think it's occuring when no data is returned from a database query then maybe you should test the result before doing an operation on it?
Dim result As String = SqlCommand.ExecuteScalar() 'just for scope'
If result Is Nothing OrElse IsDBNull(result) Then
'no result!'
End If
You can put a logging mechanism in your application so you can isolate the cause of the error. An Exception object has the StackTrace property which is a string that describes the contents of the call stack, with the most recent method call appearing first. By looking at it, you'll have more details on what might be causing the exception.
When working with databases, you can get this error when you try to get a value form a field or row which doesn't exist. i.e. if you're using datasets and you use:
Dim objDt as DataTable = objDs.Tables("tablename")
you get the object "reference not set to an instance of object" if tablename doesn't exists in the Dataset. The same for rows or fields in the datasets.
Well, Error is explaining itself. Since You haven't provided any code sample, we can only say somewhere in your code, you are using a Null object for some task. I got same Error for below code sample.
Dim cmd As IDbCommand
cmd.Parameters.Clear()
As You can see I am going to Clear a Null Object. For that, I'm getting Error
"object reference not set to an instance of an object"
Check your code for such code in your code. Since you haven't given code example we can't highlight the code :)
In case you have a class property , and multiple constructors, you must initialize the property in all constructors.