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

时间:2016-04-27 17:13:14

标签: vb.net excel-vba vba excel

我想我正在失去理智 - 如何将变量声明为字符串,然后将其设置为等于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中,对吧?

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

要从VB.NET开始使用Excel,首先必须添加对项目的引用:

it0 = iter(['foo','bar'])
it1 = iter(['bar','foo'])
it2 = iter(['foo','foo'])
it3 = iter(['bar','bar'])

try:
    a, b, c, d = map(next, (it0, it1, it2, it3), (None,)*4)
    while all(_ is not None for _ in (a,b,c,d)):
        #some operations that can raise ValueError
        if a+b+c+d == 'foobar'*2:
            a, b, c, d = map(next, (it0, it1, it2, it3), (None,)*4)
        elif a+b == 'foobar':
            c, d = map(next,(it2, it3), (None,)*2)
        else:
            a, b = map(next,(it0, it1), (None,)*2)
except StopIteration:
    pass

添加参考:

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

答案 1 :(得分:1)

您需要从应用程序对象开始。假设是AppExcel

Dim AppExcel As New Excel.Application

从那里,你可以做到:

Dim cellrange1 as Excel.Range = AppExcel.ActiveWorkbook.Sheets("MySheet").Range("SQL")

由于您已将cellrange1声明为Range,因此无法将其设置为Range("SQL").Value
Value会返回object,这是Range中包含的值。

那太啰嗦了。为了(可能)更清楚地说明,Range("SQL")会返回RangeRange("SQL").Value返回一个对象。

如果您想获得该值,那就是cellrange1.Value,或者cellrange1.Text。假设范围包含某种SQL,我会选择Text

Excel互操作编程的一个不幸的方面是许多属性返回对象而不是强类型值。例如,Range.Text返回的对象始终为string,但该属性仍返回object。这意味着Visual Studio intellisense通常不会告诉您属性返回的类型。您需要在documentation中查找属性和函数才能真正了解它们返回的内容。