在 excel-vba 中设置动态范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18491656/
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-08 16:30:31  来源:igfitidea点击:

Setting up a dynamic range in excel-vba

excelvbaexcel-vba

提问by whytheq

I'm basing my code off of this. Excel VBA - select a dynamic cell range

我的代码基于此。 Excel VBA - 选择动态单元格范围

I'm trying to find the syntax to create a dynamic range. Example: I always start on D8 but the upper bound of the range is based on an int count in another cell. [h4]

我试图找到创建动态范围的语法。示例:我总是从 D8 开始,但范围的上限基于另一个单元格中的 int 计数。[h4]

Dim count As Integer
count = Sheet2.Cells(8,1).Value
Set refRng = Sheet2.Range("D8:" & Cells(8, i).Address)

Is the relevant code sample.

是相关的代码示例。

I now know that Sheet2.Range("H1") doesn't return an int, it returns a variant or something?

我现在知道 Sheet2.Range("H1") 不返回 int,它返回一个变体或什么?

I've tried a million different things and have figured out that none of them work. There has to be a better way to set up a dynamic range.

我已经尝试了一百万种不同的东西,但发现它们都不起作用。必须有更好的方法来设置动态范围。

采纳答案by tigeravatar

This was originally a comment, but it is also the solution so I am adding it as an answer

这最初是评论,但它也是解决方案,所以我将其添加为答案

Cells(8, 1)= "A8". If you want cell H1 it would be Cells(1, 8)or Cells(1, "H"). If you want cell H4 it would be Cells(4, 8)or Cells(4, "H").

Cells(8, 1)=“A8”。如果您想要单元格 H1,它将是Cells(1, 8)Cells(1, "H")。如果您想要单元格 H4,它将是Cells(4, 8)Cells(4, "H")

Alternately, just Range("H1")or Range("H4")

或者,只是Range("H1")Range("H4")

回答by whytheq

Not 100% sure what you're trying to achieve but in terms of messing around with ranges maybe this is a start:

不是 100% 确定您要实现的目标,但在处理范围方面,这可能是一个开始:

Option Explicit

Sub select_Range()

Dim count As Integer
count = ThisWorkbook.Worksheets("Sheet2").Range("A8").Value

Dim i As Integer
i = count

Dim refRng As Excel.Range
Set refRng = ThisWorkbook.Worksheets("Sheet2").Range("D8:D" & i)

refRng.Select

End Sub

This results in the following on Sheet2:

这导致以下内容Sheet2

enter image description here

在此处输入图片说明