Excel VBA循环并从数组中获取值

时间:2016-05-09 09:50:20

标签: excel vba excel-vba

我有以下代码来检索选择,然后将其作为字符串数组。

Dim strArgument As Variant
Dim irange As Range
Dim ricosString As Variant

Set irange = Selection
ricosString = RangeToStringArray(irange)

Dim vArray As Variant
For i = LBound(ricosString) To UBound(ricosString)
    Set vArray = ricosString(i)

我的问题出在ricosString(i)上。这是一个错误Subscript out of range.任何想法为什么?

以下是RangeToStringArray

的代码
Public Function RangeToStringArray(theRange As Excel.Range) As String()

Dim variantValues As Variant
variantValues = theRange.Value

Dim stringValues() As String
ReDim stringValues(1 To UBound(variantValues, 1), 1 To UBound(variantValues, 2))

Dim columnCounter As Long, rowCounter As Long
For rowCounter = UBound(variantValues, 1) To 1 Step -1
   For columnCounter = UBound(variantValues, 2) To 1 Step -1
       stringValues(rowCounter, columnCounter) = CStr(variantValues(rowCounter, columnCounter))
   Next columnCounter
Next rowCounter

RangeToStringArray = stringValues

结束功能

3 个答案:

答案 0 :(得分:1)

RangeToStringArray是2维,但您将其引用为1维 设置vArray = ricosString(i)

Ricostring也不是一个对象,所以你不应该使用Set

答案 1 :(得分:0)

关于RangeToStringArray功能,我并不真正感兴趣:为什么不使用ricosString = irange,这会更简单,更快?

答案 2 :(得分:0)

将ricosString定义为正确的字符串数组:

Dim ricosString() As String

将RangeToStringArray函数替换为正确的函数:

Public Function RangeToStringArray(theRange As Excel.Range) As String()

Dim cell As Range
Dim values() As String
Dim i As Integer

i = 0

ReDim values(theRange.Cells.Count)

For Each cell In theRange

    values(i) = cell.Value
    i = i + 1
Next cell

RangeToStringArray = values
End Function

然后你可以像这样引用数组中的值:

vArray = ricosString(i) 'without Set