Debug your code - if you are not sure how then follow the instructions here
Tutorial: Debug Visual Basic code - Visual Studio | Microsoft Docs[
^]
Look at the line of code that is throwing the exception
rng = xlsheet.Range("A").EntireColumn
There are only two things in that line that are not part of the language syntax and those are the variables
rng
and
xlsheet
. You are trying to assign a value to
rng
and it has been properly declared within the scope of this code so it's unlikely to be that. So have a look at
xlsheet
. It is assigned a value (we think) in the line above that
xlsheet = CType(xlWorkbook.Sheets(level), Excel.Worksheet)
Excamine the variable in the debugger, you will probably find that it is "Nothing". Getting a value into
xlsheet
depends on a couple of other variables -
xlWorkbook
and
level
If
level
has not been set correctly and is 0 I would expect that to have been the line that threw the exception (excel sheets start at 1). But if you examine
xlsheet
in your IDE / Debugger you will probably find that it is "Nothing". To be honest, I'm not sure why you are using CType there - Sheets(n) will return an Excel.Worksheet, the conversion seems unnecessary.
Assuming level <> 0 then the line above
xlWorkbook = xlApp.Workbooks.Open(Path)
needs to be looked at. In your debugger does
xlWorkbook
have a value, and is the name of that workbook "AA.xlsx"? Because you have not specified a
path in
Dim Path As String = "AA.xlsx"
You can make life a lot easier for yourself when tracking down errors by using well-constructed and thought out error handling techniques. This article is a good starting point
Exception Handling Best Practices in .NET[
^] - most of the examples are in C# but the words apply to any language. VB.NET has a section to itself at the end of the article, but don't just jump straight to it - read the principles