vba output 2D an array to sheet issue

2019-09-16 13:29发布

I'm trying to output the following 2D array to a sheet in a Workbook. The code runs but the array is not visible on the sheet. Please help me find the error. Thanks

Dim R As Long, C As Long, vArr As Variant

vArr = Array(Array("N", "c.181C > a", "p.Q61K", "", "0.11"), _
              Array("C", "c.98C > a", "p.S33Y", "", "36%"), _
              Array("K", "c.2447A > T", "p.D816V", "", "8"), _
              Array("B", "c.1799T > T", "p.V600E", "", "0.08"), _
              Array("N", "c.181C > a", "p.Q61K", "", "0.11"), _
              Array("C", "c.98C > a", "p.S33Y", "", "36"), _
              Array("N", "c.181C > a", "p.Q61K", "", "0.11"), _
              Array("C", "c.98C > a", "p.S33Y", "", "36"))

  For R = LBound(vArr) To UBound(vArr)
    For C = LBound(vArr(LBound(vArr))) To UBound(vArr(UBound(vArr)))
      'MsgBox "vArr(" & R & ")(" & C & ") = " & vArr(R)(C)
    Next
  Next
LRow = Worksheets("Sheet2").Range("A" & Rows.count).End(xlUp).Row

Sheets("Sheet2").Select
Worksheets("Sheet2").Range("C" & LRow + 1 & ":G" & LRow + 9).Value = vArr

1条回答
你好瞎i
2楼-- · 2019-09-16 13:46

For one thing you were trying to paste something which had 8 rows into a range with 9 rows. But -- the more fundamental problem is that in VBA an array of arrays is different from a 2 - dimensional array. You should convert to a 2-d array before pasting:

Sub test()

    Dim R As Long, C As Long, vArr As Variant
    Dim vArr2 As Variant
    Dim LRow As Long

    vArr = Array(Array("N", "c.181C > a", "p.Q61K", "", "0.11"), _
                  Array("C", "c.98C > a", "p.S33Y", "", "36%"), _
                  Array("K", "c.2447A > T", "p.D816V", "", "8"), _
                  Array("B", "c.1799T > T", "p.V600E", "", "0.08"), _
                  Array("N", "c.181C > a", "p.Q61K", "", "0.11"), _
                  Array("C", "c.98C > a", "p.S33Y", "", "36"), _
                  Array("N", "c.181C > a", "p.Q61K", "", "0.11"), _
                  Array("C", "c.98C > a", "p.S33Y", "", "36"))

    ReDim vArr2(0 To 7, 0 To 4)
    For R = 0 To 7
        For C = 0 To 4
            vArr2(R, C) = vArr(R)(C)
        Next C
    Next R

    LRow = Worksheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Row

    Sheets("Sheet2").Select
    Worksheets("Sheet2").Range("C" & LRow + 1 & ":G" & LRow + 8).Value = vArr2

End Sub
查看更多
登录 后发表回答