首页 > 解决方案 > VBA通过函数传递范围

问题描述

我有一个关于 VBA 范围参考的问题。

我正在编写代码以将表数据导出到正常范围。出于某种原因,我无法将范围分配给我的范围变量。使用此代码,我有运行时错误:91。未设置对象变量。

从错误消息中,我了解到我的代码没有完成。我需要做更多的事情。因此可以适当设置范围。

我想知道这里缺少什么。对我来说,这是一个范围 = 范围的情况。

这是我的代码:

Function selecttable() As Range

'Intialize variables.
Dim objLB As ListObject, tablename() As String
Dim i As Integer, rng As Range

i = 1

'read through all tables in the sheet.

For Each objLB In ActiveSheet.ListObjects

ReDim Preserve tablename(1 To i + 1) ' allocate space for the data

tablename(i) = objLB.Name ' put data in the respective unit of array.

i = i + 1

Next

' pass the first table range to the "paste sub".
' This is where I have the problem.
' What is missing here?
rng = ActiveSheet.ListObjects(tablename(1)).Range

End Function

Sub paste_table()

Dim rng As Variant

selecttable().Copy

Cells(10, 12).PasteSpecial Paste:=xlPasteValues

End Sub

标签: excelvbarange

解决方案


推荐阅读