将范围保存到变量 [英] Save range to variable

查看:109
本文介绍了将范围保存到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些功能性的VBA:

  Sheets(Src)。Range(A2:A9)。目的地:=表(目的地)范围(A2)

源代码范围变为可变的变量。

  SrcRange = Sheets(Src)。Range(A2:A9)
SrcRange.Copy目的地:= Sheets(Dest)。范围(A2)

但是,这不行。
什么SrcRange应该被调暗?第一行是否正确?

我尝试调光SrcRange作为范围,它给了我

运行时错误91:对象变量或块变量未设置



我不太熟悉语言,文档让我想要(我找不到返回类型的表格索引)调用,这个是最近我发现)。当我击中记录宏时,执行一些操作,然后点击停止,宏主体仍然空白。



有没有人可以看出如何使用SrcRange作为变量?

解决方案

在你自己的答案中,你有效地这样做:

  Dim SrcRange As Range'你应该总是明确声明
Set SrcRange = Sheets(Src)。Range(A2:A9)
SrcRange.Copy目标:= Sheets(Dest)。Range(A2)

你不是真的提取范围到变量,您正在设置范围的参考。



在许多情况下,这可以更有效率和更灵活: p>

  Dim Src As Variant 
Src = Sheets(Src)。Range(A2:A9)。Value'读取范围到数组
'在这里你可以添加代码来操纵你的Src数组
'...
表格(Dest)。Range(A2)。Value = Src'Write阵列返回另一个范围


I wrote some functional VBA:

Sheets("Src").Range("A2:A9").Copy Destination:=Sheets("Dest").Range("A2")

I want to extract the source range into a variable for flexibility.

SrcRange = Sheets("Src").Range("A2:A9")
SrcRange.Copy Destination:=Sheets("Dest").Range("A2")

However, this doesn't work. What SrcRange should be Dimmed as? Is the first line even correct?
I tried Dimming SrcRange as Range and it gave me
Runtime error 91: Object Variable or With block variable not set

I'm not very familiar with the language and the documentation has left me wanting (I couldn't find the return type to the Sheets(index) invocation, this was the closest I found). When I hit Record Macro, perform some actions, and hit stop, the Macro body is still blank.

Could anyone shed some light on how to use SrcRange as a variable?

解决方案

In your own answer, you effectively do this:

Dim SrcRange As Range ' you should always declare things explicitly
Set SrcRange = Sheets("Src").Range("A2:A9")
SrcRange.Copy Destination:=Sheets("Dest").Range("A2")

You're not really "extracting" the range to a variable, you're setting a reference to the range.

In many situations, this can be more efficient as well as more flexible:

Dim Src As Variant
Src= Sheets("Src").Range("A2:A9").Value 'Read range to array
'Here you can add code to manipulate your Src array
'...
Sheets("Dest").Range("A2").Value = Src 'Write array back to another range

这篇关于将范围保存到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆