2

for each-loop を使用して VBA に Array を設定したいのですが、それができません

Dim MyArray() As Variant
Dim RowCounter As Integer
Dim ColCounter As Integer
Dim rCell As Range
Dim rRng As Range
Set rRng = Sheet1.Range("B10:Z97")
RowCounter = 0
ColCounter = 0
ReDim MyArray(rRng.Rows.Count, rRng.Columns.Count)  'Answer by @varocarbas
For Each rCol In rRng.Columns
   For Each rCell In rCol.Rows
    If IsNumeric(rCell.Value) And (Not (IsEmpty(rCell.Value))) And (Len(rCell.Value) <> 0) Then
         'ReDim Preserve MyArray(RowCounter, ColCounter) -- Old Logic which cause Error
         MyArray(RowCounter, ColCounter) = rCell.Value
         RowCounter = RowCounter + 1
    Else
        'Debug.Print rCell.Value & " is not an Integer" & vbNewLine
    End If
  Next rCell
  ColCounter = ColCounter + 1
  RowCounter = 0
Next rCol

しかしReDim Preserve MyArray(RowCounter, ColCounter)、この行で添え字エラーが発生しました。ReDim Preserve MyArray(1, 0)

Excelシートから値を読み取り、配列に入力してから、計算を行い、Excelの値の計算によってExcelの各列の最後のセルの値を更新します。

コードで更新

Function RunSquareOfVariance(temperature As Integer, cellValue As Variant) As Double
         RunSquareOfVariance = "=IF((" & temperature + cellValue & ")<0,0,(" & temperature + cellValue & "))*IF((" & temperature + cellValue & ")<0,0,(" & temperature + cellValue & "))"
End Function

コード内で次の行を変更する場合

MyArray(RowCounter, ColCounter) = RunSquareOfVariance(StantardTemperature, rCell.Value)

現在、MyArray(0,0)値ストア内=IF((-16.8)<0,0,(-16.8))*IF((-16.8)<0,0,(-16.8))

しかし、式Withingの値を保存したいMyArray(0,0) = ValueOftheFormula

4

4 に答える 4

1

私が覚えている限り、最後の配列次元のサイズのみを変更できます。

確認したところ、それは本当です。MSDNによると:

Preserve キーワードを使用すると、配列の最後の次元のみをサイズ変更でき、次元数はまったく変更できません。

サブの最終的な目標がわからないため、変更を提案することは困難です。ただし、配列の配列を使用することを検討できます。このようなソリューションの構文は次のように機能します。

Dim arrA() As Variant
Dim arrB() As Variant
...
ReDim Preserve arrA(RowCounter)
ReDim Preserve arrB(ColCounter)
...
arrA(RowCounter) = x
arrB(ColCounter) = y
...
Dim arrAB
arrAB = Array(arrA, arrB)
...
'to get elements of array you need to call it in this way:
arrAB(0)(RowCounter) >> to get x
arrAB(1)(ColCounter) >> to get y

このようなソリューションにはいくつかの欠点がありますが、他の状況で役立つ可能性があります。

于 2013-06-27T20:35:35.370 に答える
0

あなたは簡単に行うことができます:

Dim rng As Range
Dim myArray() As Variant
Set rRng =  Sheet1.Range("B10:Z97")
myArray = rRng.Value

For Each rCell In rRng.Rowsの代わりにもする必要がありFor Each rCell In rCol.Rowsます。それ以外の場合は、Kaz が言うように、配列の最後の次元のサイズしか変更できません。

于 2013-06-27T20:50:53.253 に答える