2013-06-23 46 views
0

我一直在犯同樣的錯誤,我不知道它是什麼。每次我使用For-Loop處理數組(通常嘗試讀取一個數組並在第二個數組中寫入值)時,它只取第一個數組的最後一個值,並將其寫入第二個數組的每個單個時隙陣列。For-Next Loop和Arrays - VBA

下面是我正在處理的最簡單/最短的一個副本。它應該讀取A1:A10中的值並將它們寫入B1:K1。

Sub Problem1() 
    Dim a(1 To 10) As Single 
    Dim b(1, 10) As Single 
    Dim i As Integer 



    For i = 1 To 10 
     a(i) = Range("A" + CStr(i)).Value 
    Next i 

    For i = 1 To 10 
     b(1, i) = a(i) 
    Next i 

    Range("B1:K1") = b(1, 10) 

End Sub 

回答

0

你想要的東西,更好的辦法,你可以去了解這將是:

Sub Problem1() 

Dim a(1 To 10) As Single 
Dim i As Integer 

For i = 1 To 10 
    a(i) = Range("A" + CStr(i)).Value 
Next i 

Range("B1:K1") = a 
End Sub 

至於什麼地方錯了你當前的實現,它是您分配一個單一的整個範圍一組細胞。更好的方法是循環訪問數組的內容,將其單獨輸出到每個單元格中。但是vba在本地處理(將數組輸出到一系列單元格),如上例所示。

3
Range("B1:K1") = b(1, 10) 

這隻能複製一個數組元素。

你可以做到以下幾點:

Range("B1:K1").Value = Application.WorksheetFunction _ 
    .Transpose(Range("A1:A10")) 

要存儲在陣列中的原始值會(用我的方法),要求它被宣佈爲Variant,遺憾的是:

Sub Problem1() 
    Dim a As Variant 

    a = Range("A1:A10") 

    Range("B1:K1") = Application.WorksheetFunction.Transpose(a) 
End Sub 

如果你還是想利用這兩個數組:

Sub Problem1() 
    Dim a As Variant 
    Dim b(1 To 10) As Single 
    Dim i As Integer 

    a = Range("A1:A10") 
    For i = 1 To 10 
     b(i) = a(i, 1) 
    Next i 
    Range("B1:K1") = b 
End Sub 
0
Sub Problem1() 
Dim i, j As Integer 
j = 2 

For i = 1 To 10 
    ActiveSheet.Cells(1, j).Value = ActiveSheet.Range("A" & i) 
    j = j + 1 
Next i 
End Sub 
+0

您可以消除'j',只是使用'I + 1'。另外,請注意你在這裏聲明'i'是一個'Variant'。看看這個[Chip Pearson page](http://www.cpearson.com/excel/DeclaringVariables.aspx)並向下滾動到「注意用一個聲明聲明的變量」。 –

0

儘量讓步驟儘可能清晰,並且在一個步驟中讀取/寫入所有值以避免輸出更改輸入(重疊單元格)。流程應該是[Read]->[Calc]->[Write]

Sub Problem1() 
    Dim a() as Variant, b() as Variant, i as Integer 

    'Get Values 
    a = Range("A1").Resize(10,1).Value2 

    'Transform the arrays in any way you need. 
    'Make sure the intent is clear 
    ReDim b(1 to 1, 1 to 10) 
    For i=1 to 10 
     b(1,i) = a(i,1) 
    Next i 

    'Set Values 
    Range("B1").Resize(1,10).Value2 = b 

End Sub 
1
Sub Problem1() 
    Dim a(1 To 10) As Single 
    Dim b(1, 10) As Single 
    Dim i As Integer 

    For i = 1 To 10 
     a(i) = Range("A" + CStr(i)).Value 
    Next i 

    For i = 1 To 10 
     b(1, i) = a(i) 
    Next i 

    Range("B1:K1") = b() 
End Sub 
+0

我在vba中並不完美。但上面給出了你正在尋找的輸出 –