在VBA中将单元格文本添加到数组中

时间:2014-06-25 15:49:51

标签: arrays excel vba

我一直在努力研究这一段时间。我正在尝试编写一个函数,它将在B列中找到最后一个填充的行(从B9开始),并将B列中的字符串值添加到数组中。

非常感谢任何帮助,谢谢大家。

Option Explicit
Function locationSum2(location) As Integer

Dim arrayLength As Integer
arrayLength = LastRowInColumn(2) - 9

Dim arrayPosition As Integer

Dim locationColumn() As String
ReDim locationColumn(0 To arrayLength) As String

Dim celltext As String
Dim i As Integer

For i = 0 To i = arrayLength
    celltext = Cells((9 + i), 2).Text
   locationColumn(i) = celltext
Next i

For arrayPosition = 0 To arrayPosition = UBound(locationColumn)
    If location = locationColumn(arrayPosition) Then
        locationSum2 = locationSum2 + Cells(arrayPosition + 9, 11).Value
    End If
Next arrayPosition

locationSum2 = locationSum2

End Function

在发表评论之后,我还将代码切换为基本上只是一个循环,它检查B列中所有内容的参数而不是制作数组。

Option Explicit
Function locationSum2(location) As Integer

Dim LastRow As Integer
LastRow = LastRowInColumn(2)

Dim i As Integer

For i = 9 To i = LastRow
    If location = Cells(i, 2).Text Then
        locationSum2 = locationSum2 + Cells(i, 11).Value
    End If
Next i

locationSum2 = locationSum2

无论出于何种原因,它似乎仍然没有正确读取B列。它返回的值为0,因此它似乎没有找到匹配。

1 个答案:

答案 0 :(得分:0)

您未正确设置for循环。

For i = 9 To i = LastRow

应该是

For i = 9 To LastRow

我不确定你是否只是问题,但让我们从那里开始