2014-10-01 26 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