[英]How to properly reference a Table from an inactive Sheet for RowSource property in Excel VBA
I am trying to fill a ListBox
in a Userform
through the RowSource
property and a Table
object containing the information in an inactive Sheet
named Data
, using Excel VBA.我正在尝试使用 Excel VBA 通过
RowSource
属性和包含名为Data
的非活动工作Sheet
中的信息的Table
对象填充用户Userform
的ListBox
。 My code mostly works, but has a serious flaw: it only works when the Sheet
containing the Table
with the data is active (selected between all the sheets in the workbook).我的代码大多工作原理,但有一个严重的缺陷:当它仅适用
Sheet
包含Table
与数据是有效的(在工作簿中的片材之间的所有选择)。
The code I tried is the following:我试过的代码如下:
ListBox1.RowSource = Worksheets("Data").Range("Table 1[[Column1]:[Column4]]").Address(0, 0)
The issue is that the range returned doesn't refer to any Sheet
, it simply is something like B2:E5
which just adds blank rows to ListBox1
.问题是返回的范围不引用任何
Sheet
,它只是类似于B2:E5
东西,它只是向ListBox1
添加空白行。 The range returned by the code should be something like Data!B2:E5
.代码返回的范围应该类似于
Data!B2:E5
。 My problem is that I can't just hard code this.我的问题是我不能只是硬编码这个。 For the sample code I simplified the reference, but the
Table
chose to get the data from will vary (all these tables are on the same Sheet
).对于示例代码,我简化了参考,但选择从中获取数据的
Table
会有所不同(所有这些表都在同一个Sheet
)。
The Address
property has several other parameters. Address
属性还有其他几个参数。 You need to include the External parameter您需要包含外部参数
.Address(0, 0, ,1)
ie IE
ListBox1.RowSource = Worksheets("Data").Range("Table1[[Column1]:[Column4]]").Address(0, 0, ,1)
Explanation:解释:
Worksheets("Data").Range("Table1[[Column1]:[Column4]]")
correctly return a range reference to the Data
sheet. Worksheets("Data").Range("Table1[[Column1]:[Column4]]")
正确返回对Data
表的范围引用。 The .Address(0, 0)
returns just the Row/Column part of that address (eg as you say B2:E5
) .Address(0, 0)
仅返回该地址的行/列部分(例如,如您所说的B2:E5
)B2:E5
to the RowSourse
property, that tells the ListBox to get the data from that address on the ActiveSheetB2:E5
写入RowSourse
属性时,它会告诉 ListBox 从ActiveSheet 上的该地址获取数据Address(0, 0, ,1)
returns a fully qualified reference, including the Workbook and Worksheet Address(0, 0, ,1)
返回一个完全限定的引用,包括工作簿和工作表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.