要在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