vba 使用变量 Rownumber 设置范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21119102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 01:22:47  来源:igfitidea点击:

Set Range with variable Rownumber

excel-vbavbaexcel

提问by ruedi

I want to set a Range. The value 10 is not fix and written in cell D1. How can i modify

我想设置一个范围。值 10 未固定并写入单元格 D1。我该如何修改

Range("A1:A10,C1:C10")

to get the Range i want.

得到我想要的范围。

I tried

我试过

Range("A1:A" & Range("D1") & , "C1:C" & Range("D1")) 

but get the error "method range of object _global failed".

但得到错误“对象_global 的方法范围失败”。

回答by Floris

Usually best to keep your code clean:

通常最好保持你的代码干净:

Dim lastRow
Dim variableRange as Range

lastRow = Range("D1").Value

Set variableRange = Range("A1:A" & lastRow & ", C1:C" & lastRow) 

Most likely your problem was in the & ,bit... The comma needed to be inside the quotation marks.

很可能你的问题出& ,在位......逗号需要在引号内。

Note that by creating a separate variable lastRow, it is immediately obvious to anyone reading the code what it is doing - the variable name becomes "micro documentation".

请注意,通过创建一个单独的变量lastRow,任何阅读代码的人都会立即明白它在做什么——变量名变成了“微文档”。

回答by Dmitry Pavliv

Try this one:

试试这个:

Range("A1:A" & Range("D1") & ", C1:C" & Range("D1"))

回答by Axel Stache

If you want to have it even less confusing than Floris' solution (which already improved readability), you may try this:

如果你想让它比 Floris 的解决方案(已经提高了可读性)更容易混淆,你可以试试这个:

Dim lastrow As Integer
Dim variablerange As Range
lastrow = Cells(1, 4)

Set variablerange = Range(Cells(1, 1), Cells(lastrow, 3))