Question "Variable used before it's assigned"

Eebigdog

Member
Joined
Sep 13, 2013
Messages
5
Programming Experience
10+
Hello,

Can anyone help to explain why I'm getting the Error: Variable 'objSht' is used before it's assigned
in my code snippet below:


If
reqXLSS Then
'Start Excel and get Application object...
objXL = CreateObject("Excel.Application")
objXL.Visible =
True
'Get new workbook
objWrkBk = objXL.Workbooks.Open("C:\Temp\HLDRC_Proj.xlsx") 'new SS...clears out any previous data.
objSht = objWrkBk.Worksheets("Sheet1")
objSht.Name =
"HLDRC Object Lists"'add tab name to the first tab.....
objSht.Cells(1, 2).Value = "Project Name"'add some dummy data....
objSht.Cells(1, 3).Value = "Date"'add some dummy data....
EndIf

'[more code in here....]
 
'Clear out anything left in the Extraction_ListBox....
frmMain.Extraction_ListBox.Items.Clear()
strListItem =
"OBJECT LIST COLLECTION:"
Call AddToListBox(strListItem)
If reqXLSS Then
objSht.Cells(1, 1).Value = "OBJECT LIST COLLECTION" <<=== Error: Variable 'objSht' is used before it's assigned.
EndIf


Question: Is the compiler that pickey that it doesn't recognize the objSht assignment within my 'If' statement?

Thanks for any help,
Grant
 
It only assigned within the If block when expression is True, so it is possible it is not assigned.
 
...understood, but my second 'If' (the one with the 'objSht') also needs to be True for the same boolean variable.
Again, depending upon how "smart" the compiler is, it should allow this sort of coding...or, am I totally "off" on this subject?
 
Compiler is not smart enough to analyze the code so far into different code blocks. You can get around it by assigning Nothing to that variable initially. That is just for your own sake and to rid that warning though, you are then on your own for this basic compiler help if you later make a coding mistake that makes use of such 'unassigned' variable.
 
Thanks John!

I moved all of my Excel declarations (Dim's) up to the top of my module and made them 'Public'.
This seems to fix my problem.
 
It generally makes sense to declare variables with the closest scope possible, declaring at the class level is the opposite of that. Also, class level variables (field) should never be Public, they should be Private, use properties when you need to expose object state outside the class. These are OOP principles.
 
Back
Top