我想我疯了 - 你如何将变量声明为字符串,然后将其设置为等于 VB.NET 中 Excel 工作簿中的范围?在 VBA 中,这很容易:
Dim SQL as string
SQL = ActiveWorkbook.Sheets("MySheet").Range("SQL")
如果我尝试在 VB.NET(在 Visual Studio 2015 中)做这样的事情,首先我找不到 Activeworkbook。其次,如果我尝试
Excel.Range("SQL")
,我收到一条错误消息,指出 'Range' is an interface type and cannot be used as an expression
.此外,它看起来不像 Range
数据类型也存在。这个功能肯定存在于 VB.NET 中,对吧?谢谢您的帮助!
最佳答案
要从 VB.NET 开始使用 Excel,首先必须添加对 Project 的引用:
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")
关于vb.net - 将变量定义为范围 - VB.NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36896540/