vb.net - 将变量定义为范围 - VB.NET

标签 vb.net excel vba

我想我疯了 - 你如何将变量声明为字符串,然后将其设置为等于 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/

相关文章:

c# - 按字母顺序和类型对列表进行排序

excel - WorksheetFunction.CountA - 升级到 Office 2010 后无法正常工作

vba - 标记轮廓与系列线的线宽

excel - 挑战 : MS Excel VBA Programming for the Absolute Beginner

VBA 列出子文件夹中的所有文件(快速方式),无需 FileSystemObject

c# - 如何将新的 MVC C# 项目与现有的 Web 窗体 VB.NET Web 应用程序项目集成?

.net - 你如何在 vb.net 中解析 HTML

vb.net - 创建数组时什么时候需要使用 `New` 关键字?

sql - MS Access - 在 VBA 中按名称执行保存的查询

sql - 将mysql迁移到sql server 2008