Reputation: 953
Hello guys! I'm really new to Visual Basic and Excel so i don't know if there's a better way to do what i'm trying to do, but this is not important.
I'm trying to set the range for formatting my excel cells with some borders and stuff like that. I don't know how to find the last used cell so i came up with this.
range = "A1:AD1"
For Each dataRow In dataTable.Rows
rowIndex += 1
Next
I created the excel sheet from my data table so they have the same columns and rows. My range was calculated earlier and it depends of how many columns i have in my excel sheet (data table/excel columns could change depending on user input)
after counting every rows in my data table i did this:
range = range.Substring(0, range.Length() - 1) & Convert.ToString(rowIndex)
The result of last line is "A1:AD413". I checked it on my excel and last used cell is exactly AD413
Now, when i try to apply my style on my range, excel throws HRESULT: 0x800A03EC
exception and I know that is something like "Out of range exception". Why excel is throwing it? how can I fix it? The range isn't wrong!
Line where excel throws exception
wSheet.Cells(range).VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter
My code
rowIndex = 0
For Each dr In dt.Rows
rowIndex += 1
Next
range = range.Substring(0, range.Length() - 1) & Convert.ToString(rowIndex + 1)
wSheet.Cells(range).VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter
wSheet.Cells(range).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft
wSheet.Cells(range).Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
Upvotes: 0
Views: 1121
Reputation: 2350
Cells() takes two integer parameters for row and column, or a string parameter for a single cell address. If you want to target a range, you need to use Worksheet.Range instead of Worksheet.Cells. Worksheet.Range can accept a starting and ending cell address, such as:
wSheet.Range("A1", "AD413").Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
In your case, since you already have the string "A1:AD413" in a variable called range, you could just change the cell-formatting lines to:
wSheet.Range(range.Split(":")(0), range.Split(":")(1)).Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
Upvotes: 1