将2维范围(i,j)的存储值重新计算N次到2维范围(N,i * j)

时间:2017-05-17 15:02:19

标签: arrays excel vba excel-vba

我有这样的二维范围(i,j):

allowUpload="{Boolean}false"

我想将其复制并粘贴到另一张表格中,如下所示:

granite/ui/components/foundation/form/fileupload

我需要多次重新计算2-dim范围并将结果存储在另一张纸上,其中每行存储一次迭代。 现在我使用两个for循环将所有计算存储在一个数组(N,i * j)中,然后将所有迭代粘贴到另一个工作表上。

有更快的方法吗? 目前的代码:

1 2 3 4 5
6 7 8 9 0

UPD: 在每次“计算”初始范围变化的值之后。该示例仅说明了如何将2-d范围的值存储在一行中。

UPD2: 更正了我当前的代码

4 个答案:

答案 0 :(得分:1)

这样的事情对你有用:

Sub tgr()

    Dim rData As Range
    Dim iter As Long
    Dim lNumIterations As Long
    Dim i As Long, j As Long, k As Long
    Dim a() As Double
    Dim aAfterCalc As Variant

    Set rData = Sheets("Data").Range("A1:E2")
    lNumIterations = 100
    ReDim a(1 To lNumIterations, 1 To rData.Rows.Count * rData.Columns.Count)

    For iter = 1 To lNumIterations
        k = 0
        Calculate
        aAfterCalc = rData.Value
        For j = 1 To rData.Columns.Count
            For i = 1 To rData.Rows.Count
                k = k + 1
                a(iter, k) = aAfterCalc(i, j)
            Next i
        Next j

    Next iter

    Sheets("results").Range("A1").Resize(lNumIterations, UBound(a, 2)).Value = a

End Sub

答案 1 :(得分:0)

不确定我能得到你,但这样的事情

or

答案 2 :(得分:0)

Private Sub this()
    Dim this As Variant, counter As Long, that As Integer, arr() As Variant
    counter = 0
    this = ThisWorkbook.Sheets("Sheet3").UsedRange
    For i = LBound(this, 2) To UBound(this, 2)
            counter = counter + 2
            ReDim Preserve arr(1 To 1, 1 To counter)
            arr(1, counter - 1) = this(1, i)
            arr(1, counter) = this(2, i)
    Next i
    ThisWorkbook.Sheets("Sheet4").Range(ThisWorkbook.Sheets("Sheet4").Cells(1, 1), ThisWorkbook.Sheets("Sheet4").Cells(1, counter)).Value2 = arr
End Sub

答案 3 :(得分:0)

试试这个。它提供了您想要的输出,只使用两个循环(而不是三个)

' For loop
Dim i As Long, j As Long
' Initalise array
Dim tmp(1 To 100, 1 To 10) As Variant

'Loop through all rows in already initalised array
For i = LBound(tmp, 1) To UBound(tmp, 1)
    'Calculate to get updated row contents
    Calculate
    'Loop through each column in row
    'The Round and divided by two is to calculate the number of columns concerned instead of the number in the array
    For j = LBound(tmp, 2) To Round((UBound(tmp, 2) + 0.1) / 2)
        'First row
        tmp(i, (j + j - 1)) = Cells(1, j).Value2
        'Second row
        ' If incase the array is initalised to an odd number otherwise this would be out of range
        If j * 2 <= UBound(tmp, 2) Then
            tmp(i, j * 2) = Cells(2, j).Value2
        End If
    Next j
Next i
' Write back to sheet
With Sheets("results").Cells(1, 1)
    Range(.Offset(0, 0), .Offset(UBound(tmp, 1) - 1, UBound(tmp, 2) - 1)) = tmp
End With