VBA Excel - 基于单元格范围值的循环

时间:2011-10-03 17:24:03

标签: arrays excel vba loops

所以我正在运行一个循环来从另一个工作表上的一个列中获取数据,并且我希望它在列中的数据结束后停止,但是我在查找结束循环的条件时遇到了一些麻烦。

Do While values(i) <> 0

Set xcell = Range(Cells(x + 3, 2), Cells(x + 3, 2))
Set ycell = Range(Cells(y + 3, 2), Cells(y + 3, 2))
x = x + 1
y = y + 1

ycell.Formula = "='\\Drcs8570168\shasad\[CR Status.xlsx]Sheet1'!" & xcell.Address

values(i + 1) = xcell.Value
i = i + 1

Loop

我尝试将每个单元格分配给带有数组的变量并运行循环,直到开始记录空白单元格。它告诉我下标超出了范围。

3 个答案:

答案 0 :(得分:2)

首先,而不是:

Set xcell = Range(Cells(x + 3, 2), Cells(x + 3, 2))

仅使用:

Set xcell = Cells(x + 3, 2)

但是,我怀疑你甚至需要循环。尝试这样的事情:

Dim vValues As Variant

'// Get the range of cells you want to work with
With Range("B3", Cells(Rows.Count, "B").End(xlUp))
    '// Add the formula, excel will automatically fill in series
    .Formula = "='\\Drcs8570168\shasad\[CR Status.xlsx]Sheet1'!A1"
    '// Build an array from the values
    vValues = .Value
End With

答案 1 :(得分:1)

您可以尝试使用函数查找包含数据的最后一行,例如:

Function LastRow(wks As Worksheet) As Long
    On Error GoTo ErrHandle
    LastRow = wks.Cells.Find("*", After:=wks.Cells(1, 1), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    Exit Function
ErrHandle:
    LastRow = 0
End Function

答案 2 :(得分:1)

您是否已初始化变量i和数组values

循环之前:

i=0
Redim Preserve valus(i)
values(i)=1 'or else we will never enter the loop

在循环中(循环语句之前的最后一行):

i = i + 1
Redim Preserve values(i)
values(i) = xcell.Value

但您甚至不需要数组values(即如果您不在代码中的任何其他地方使用它),只需将最后一个单元格值存储在i中。

循环之前:

i = 1 'or we won't enter the loop
while i<>0 'starting the loop

这里是循环代码,然后是循环结束之前:

i = xcell.Value
Loop

编辑: 但是如果列表中的实际值为0作为单元格值,则循环将在列表结尾之前停止,因此您可能需要检查单元格是否不包含字符:

假设:

Dim i as Variant

最后一个例子中的循环条件也可以是:

while i<>""

只有当单元格真的为空(=没有内容)时才会停止

相关问题