2014-10-01 56 views
0

我还不熟悉VBA Excel编码。请告诉我是否有任何需要改进的地方。你如何计算字符串VBA Excel的列表?

在下面的例子中,我试图从生成类中获取偶数值的列表并插入到excel vba表中。但是,我如何计算返回的列表数?

Private Function Generate() 
    Dim red(1 To 20) As String 
    For i = 1 To 20 
     red(i) = i * 2 
    Next i 
    Generate = red() 
End Function 

Sub Format() 
    Dim str() As String 
    str() = Generate 
    Range("A1").Select 
    With Selection 
     For i = 1 To str().Count    'what do I do with this? Obviously str().Count is not working. 
      .Offset(1, i).Value = str(i) 
     Next 
    End With 
End Sub 

谢谢。

回答

0

设法解决我自己和这里的答案:

Private Function Generate() 
    Dim red(1 To 20) As String 
    For i = 1 To 20 
     red(i) = i * 2 
    Next i 
    Generate = red() 
End Function 

Sub Format() 
    Dim str() As String 
    str() = Generate 

    Range("A1").Select 
    With Selection 
     For i = LBound(str) To UBound(str) 
      .Offset(i - 1, 0).Value = str(i) 
     Next 
    End With 
End Sub 
+0

你仍然可以消除'范围( “A1”)Select'线和使用'对于i = 1至UBOUND(STR)。 '然后'Range(“A”&i).Value = str(i)'。如果你的数组不是1,那么你将1改为'lbound(str)' – 2014-10-01 07:31:14

+0

赞赏以获取建议。 – 2014-10-01 07:43:16

+0

您可以将红色声明为二维数组:'红色(1至20,1至1)';将值赋给第一维'red(i,1)= i * 2'的元素;然后,在Format宏中,只使用单行(无循环或select):Range(“A1”)。Resize(ubound(str))= str' – 2014-10-01 08:46:43