我无法通过我在vb 2010中开发的应用程序保存Excel工作表。它能够创建一个文件并输入分配的所有数据,但在命中保存命令时未处理COM异常: -
xlWorkBook.SaveAs(“C:\ ABC”,“xlsx”)
我在我的visual studio 2010中添加了对excel的引用。
以下是我正在使用的代码: -
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
'Add a New Workbook
xlWorkBook = xlApp.Workbooks.Add
'Display Excel
xlApp.Visible = False
'Set the relebant sheet that we want to work with
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
With xlWorkSheet
'Directly type the values that we want
.Range("A1").Value = "Company Name"
.Range("A2").Value = "Product Name"
.Range("A3").Value = "Budget"
.Range("A4").Value = "Expected Delivery"
.Range("B1").Value = "hi"
.Range("B2").Value = "hh"
.Range("B3").Value = "qw"
.Range("B4").Value = "qw"
End With
'Save the file
xlWorkBook.SaveAs("C:\ABC", "xlsx")
'Close the file
'xlWorkBook.Close()
End Sub
答案 0 :(得分:2)
使用:
{{1}}
答案 1 :(得分:0)
将代码更改为:
''Add a New Workbook
Dim AppExcel As New Excel.Application
Dim Classeur As Excel.Workbook = AppExcel.Workbooks.Add()
Dim xlWorkSheet As Excel.Worksheet = Classeur.ActiveSheet
'Display Excel
AppExcel.Visible = False
'Set the relebant sheet that we want to work with
With xlWorkSheet
'Directly type the values that we want
.Range("A1").Value = "Company Name"
.Range("A2").Value = "Product Name"
.Range("A3").Value = "Budget"
.Range("A4").Value = "Expected Delivery"
.Range("B1").Value = "hi"
.Range("B2").Value = "hh"
.Range("B3").Value = "qw"
.Range("B4").Value = "qw"
End With
'Save the file
xlWorkSheet.SaveAs("C:\ABC3.xlsx"
答案 2 :(得分:0)
以上答案似乎都是正确的,但缺乏解释。
表达式.SaveAs(FileName,FileFormat,Password,WriteResPassword, ReadOnlyRecommended,CreateBackup,AccessMode,ConflictResolution, AddToMru,TextCodepage,TextVisualLayout,Local)
以上是excel SaveAs
方法所有参数都是可选的。
Filename
Optional
Variant
一个字符串,指示要保存的文件的名称。您可以 包括一条完整的道路;如果不这样做,Microsoft Excel将保存该文件 当前文件夹。
上面的重要部分是你遗漏的名字。
FileFormat
Optional
Variant
保存文件时使用的文件格式。有效的列表 选择,请参阅XlFileFormat枚举。对于现有文件, 默认格式是指定的最后一种文件格式;对于一个新文件, default是正在使用的Excel版本的格式。
由于您指定了没有文件名的路径,因此出现错误。 改变这一行
xlWorkBook.SaveAs("C:\ABC", "xlsx")
要 xlWorkBook.SaveAs( “C:\ ABC.xlsx”) 修复了一个问题。
答案 3 :(得分:0)
Imports Excel = Microsoft.Office.Interop.Excel
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
xlWorkBook = xlApp.Workbooks.Add
xlApp.Visible = False
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
With xlWorkSheet
'Directly type the values that we want
.Range("A1").Value = "Company Name"
.Range("A2").Value = "Product Name"
.Range("A3").Value = "Budget"
.Range("A4").Value = "Expected Delivery"
.Range("B1").Value = "hi"
.Range("B2").Value = "hh"
.Range("B3").Value = "qw"
.Range("B4").Value = "qw"
End With
xlWorksheet.SaveAs("C:\ABC", "xlsx")
End Sub