Excel throws HRESULT: 0x800A03EC exception when using Range

大兔子大兔子 提交于 2021-01-29 10:55:48

问题


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: 0x800A03ECexception 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

回答1:


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


来源:https://stackoverflow.com/questions/49794573/excel-throws-hresult-0x800a03ec-exception-when-using-range

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!