(VBA)尝试创建一个包含4行和n列的数组

问题描述 投票:0回答:1
Sub abcd()

Dim numcomps As Integer
numcomps = Range("B3").Value
Dim constants() As Integer
ReDim constants(1 To 4, 1 To numcomps)
Dim i As Integer, j As Integer, k As Integer, compnum As Integer

For k = 1 To numcomps
compnum = Cells(k, 7).Value
   For i = 1 To 4
   constants(i, k) = Cells((compnum + 6), (i + 2)).Value

   Next i
Next k

MsgBox (constants(1, 1))
MsgBox (constants(2, 1))
MsgBox (constants(3, 1))


End Sub

基本上,我正在尝试创建一个包含4行和n列的数组,其中n由用户作为numcomps给出。每列将包含从电子表格中的表中收集的4个常量。代码似乎每次循环时都会重写数组中的值,而不是创建新列。我需要添加/更改什么?

arrays excel vba
1个回答
0
投票

尝试此自定义从何处开始收集数据

Sub MultiDArray()

    ' Define variables
    Dim arrayColumns As Integer
    Dim arrayRows As Integer
    Dim constants() As Integer
    Dim initialRow As Integer
    Dim initialColumn As Integer
    Dim rowCounter As Integer
    Dim columnCounter As Integer

    ' Define how many rows
    arrayRows = 4

    ' Define how many columns
    arrayColumns = Range("B3").Value

    ' Define row to begin gathering data
    initialRow = 7

    ' Define column to begin gathering data
    initialColumn = 2

    ' Redimension array to number of rows and columns
    ReDim constants(1 To arrayRows, 1 To arrayColumns)


    ' Loop through each row
    For rowCounter = 1 To arrayRows

        ' Loop through each column
        For columnCounter = 1 To arrayColumns

            ' Gather data into array
            constants(rowCounter, columnCounter) = Cells(rowCounter + initialRow, columnCounter + initialColumn)

            ' For debugging purposes
            Debug.Print "Cell: " & Cells(rowCounter + initialRow, columnCounter + initialColumn).Address, "Row: " & rowCounter, "Column: " & columnCounter, "Value:" & constants(rowCounter, columnCounter)

        Next columnCounter

    Next rowCounter

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.