我在循环和创建MS Excel文档时遇到了一些麻烦,下面的代码片段
Private Sub selectedRowsButton_Click( _
ByVal sender As Object, ByVal e As System.EventArgs) _
Handles selectedRowsButton.Click
Dim selectedRowCount As Integer = _
DataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected)
If selectedRowCount > 0 Then
Dim sb As New System.Text.StringBuilder()
Dim objexcel As New Excel.Application
Dim i As Integer
Dim FACode As Integer
Dim Sitename As Integer
Dim Sitecode As Integer
Dim Address As Integer
Dim City As Integer
Dim State As Integer
Dim ZIP As Integer
FACode = 1
Sitename = 5
Sitecode = 2
Address = 6
City = 7
State = 9
ZIP = 10
Dim xlWorkbook As Excel.Workbook
xlWorkbook = objexcel.Workbooks.Open("template path")
For i = 0 To selectedRowCount - 1
objexcel.Visible = True
objexcel.Range("B2").Value = DataGridView1.SelectedCells(Sitename).Value.ToString()
objexcel.Range("B3").Value = DataGridView1.SelectedCells(Sitecode).Value.ToString()
objexcel.Range("B5").Value = DataGridView1.SelectedCells(FACode).Value.ToString()
Dim thisfile As Object
thisfile = objexcel.Range("B5").Value & "." & _
objexcel.Range("B3").Value & "." & "otherstring" & "." & "otherstring2" & "." & ".xls"
With objexcel
xlWorkbook.SaveAs(Filename:="c:\test\" & thisfile)
'~~> Close the Excel file without saving
xlWorkbook.Close(False)
End With
Next i
End If
我从HRESULT得到错误Exception:0x800A03EC用于语句
objexcel.Range("B2").Value = DataGridView1.SelectedCells(Sitename).Value.ToString()
如果在创建程序之前我只选择了一行DataGrid,那么当我选择多行时会发生此错误。因为我正在创建专门用于多行选择的程序,所以我很难理解我出错的地方。任何帮助或指示赞赏,谢谢!
答案 0 :(得分:0)
两件事
您已将objexcel
声明为Excel.Application
,因此您不应使用objexcel.Range("B2").Value
。使用xlWorkbook.Range("B2").Value
。在代码中随处更改。
您不能像这样使用SaveAs
。请参阅下面的快照。如果要保存为xls文件,则必须使用FileFormat:=56
请参阅此代码示例
'~~> Save As file
xlWorkbook.SaveAs(Filename:="c:\test\" & thisfile, FileFormat:=56)
如果您未指定文件格式,则在打开文件后打开文件时会收到错误消息。
您可能希望查看有关如何从VB.Net自动化Excel的此链接
主题:VB.NET和Excel
链接:http://www.siddharthrout.com/vb-dot-net-and-excel/
我不太确定你究竟想用DGV做什么。就像肖恩提到的那样,你没有增加价值。如果您可以发布DGV外观的快照以及导出后Excel文件的外观,那么我们可以更好地帮助您:)