要在Excel中工作,因为VB.NET,首先必须将引用添加到您的项目:
Microsoft.Office.Interop
,要添加一个参考:
在Solution Explorer
,右键单击References
节点上选择Add Reference
。
导入参考在代码:
Imports Microsoft.Office.Interop
尝试使用此代码:
Dim AppExcel As New Excel.Application 'Create a new Excel Application
Dim workbook As Excel.Workbook = AppExcel.Workbooks.Add() 'Create a new workbook
Dim sheet As Excel.Worksheet = workbook.Sheets("Sheet1") ' Create variable a Sheet, Sheet1 must be in WorkBook
'Work with range
Dim cellRange1 As Excel.Range = sheet.Range("A1") 'Range with text address
cellRange1.Value = "Text in Cell A1"
Dim cellRange2 As Excel.Range = sheet.Cells(2, 2) 'Range("B2:B2") with index; Cells(N°Row,N°Col)
cellRange2.Value = "Text in Cell B2"
Dim tableRange3 As Excel.Range = sheet.Range("A1:F4") 'Range with text address
Dim tableRange4 As Excel.Range = sheet.Range(sheet.Cells(1, 1), sheet.Cells(4, 6)) 'Range("A1:F4") with index; Cells(N°Row,N°Col)
AppExcel.Visible = True 'To display the workbook
代码,而可变片
Dim AppExcel as New Excel.Application
Dim workbook As Excel.Workbook = AppExcel.Workbooks.Add()
'Range
Dim cellrange1 as Excel.Range = AppExcel.ActiveWorkbook.Sheets("Feuil1").Range("A1")
对不起,我忘了提及我已经有了那个参考,我想。它显示为Microsoft.Office.Interop.Excel。那是正确的吗?我认为只有在我不想写出所有对象限定符时才需要Imports语句。没有必要,是吗? 你是上面的例子,但为什么我不能这样做: Dim AppExcel as New Excel.Application Dim cellrange1 as Excel.Range = AppExcel.ActiveWorkbook.Sheets(“MySheet”)。Range(“SQL “)。值。 我不喜欢在其他变量中嵌套变量,但我上面写的东西在Visual Studio中似乎不起作用。 谢谢! – christopheralan88
首先,您不能这样做,因为您必须创建一个WorkBook对象,并且不能将对象类型指定给Range类型。第二个为什么把SQL放在代表SQL的范围(“SQL”)中;必须是地址范围。 –
为什么我不能将对象类型分配给Range变量?那么我将如何分配一个范围的值/文本呢?我是VB.NET新手,但我相信你可以引用一个命名范围,对吗?如果单元格A1被命名为“BudgetSQL”,那么将“BudgetSQL”放在Range对象的Cell1参数中应该没问题,对吧? – christopheralan88