수색…


VBA에서 배열 선언

배열 선언은 변수 선언과 매우 유사합니다. 단, 이름 바로 뒤에있는 Array의 차원을 선언해야한다는 점이 다릅니다.

Dim myArray(9) As String 'Declaring an array that will contain up to 10 strings

기본적으로 VBA의 배열 은 ZERO로부터 인덱싱 되므로 괄호 안의 숫자는 배열의 크기를 나타내지 않고 마지막 요소의 인덱스를 나타냅니다

요소에 접근하기

배열의 요소에 액세스하려면 배열의 이름 뒤에 괄호 안에있는 요소의 색인을 사용합니다.

myArray(0) = "first element"
myArray(5) = "sixth element"
myArray(9) = "last element"

배열 인덱싱

이 줄을 모듈의 맨 위에 배치하여 배열 색인을 변경할 수 있습니다.

Option Base 1

이 행을 사용하면 모듈에서 선언 된 모든 배열의 색인생성됩니다 .

특정 색인

To 키워드와 상한 및 하한 (= 인덱스)을 사용하여 자체 인덱스로 각 배열을 선언 할 수도 있습니다.

Dim mySecondArray(1 To 12) As String 'Array of 12 strings indexed from 1 to 12
Dim myThirdArray(13 To 24) As String 'Array of 12 strings indexed from 13 to 24

동적 선언

선언 이전에 Array의 크기를 모를 때는 동적 선언과 ReDim 키워드를 사용할 수 있습니다.

Dim myDynamicArray() As Strings 'Creates an Array of an unknown number of strings
ReDim myDynamicArray(5) 'This resets the array to 6 elements

ReDim 키워드를 사용하면 Array의 이전 내용을 지울 수 있습니다. 이를 막기 위해 ReDim 다음에 Preserve 키워드를 사용할 수 있습니다.

Dim myDynamicArray(5) As String
myDynamicArray(0) = "Something I want to keep"

ReDim Preserve myDynamicArray(8) 'Expand the size to up to 9 strings
Debug.Print myDynamicArray(0) ' still prints the element

Split을 사용하여 문자열에서 배열 만들기

스플릿 함수

지정된 부분 문자열을 포함하는 0부터 시작하는 1 차원 배열을 반환합니다.

통사론

분할 (표현식 [, 구분 기호 [, 제한 [, 비교 ]]] )

부품 기술
표현 필수 사항. 하위 문자열과 구분 기호가 포함 된 문자열 식입니다. expression 이 길이가 0 인 문자열 ( ""또는 vbNullString) 인 경우 Split 은 요소가없고 데이터가없는 빈 배열을 반환합니다. 이 경우 반환 된 배열의 LBound는 0이고 UBound는 -1입니다.
구분 기호 선택 과목. 하위 문자열 제한을 식별하는 데 사용되는 문자열 문자입니다. 생략되면 공백 문자 ( "")가 구분 기호로 간주됩니다. delimiter 가 길이가 0 인 문자열이면 전체 표현식 문자열을 포함하는 단일 요소 배열이 반환됩니다.
한도 선택 과목. 반환 할 부분 문자열의 수. -1은 모든 하위 문자열이 반환됨을 나타냅니다.
비교 선택 과목. 하위 문자열을 평가할 때 사용할 비교 유형을 나타내는 숫자 값입니다. 값은 설정 섹션을 참조하십시오.

설정

compare 인수는 다음 값을 가질 수 있습니다.

일정한 기술
기술 -1 Option Compare 문 설정을 사용하여 비교를 수행합니다.
vbBinaryCompare 0 이진 비교를 수행합니다.
vbTextCompare 1 텍스트 비교를 수행합니다.
vbDatabaseCompare 2 Microsoft Access 전용. 데이터베이스의 정보를 기반으로 비교를 수행합니다.

이 예제에서는 Split이 여러 스타일을 보여줌으로써 어떻게 작동하는지 보여줍니다. 주석에는 수행 된 다른 Split 옵션 각각에 대한 결과 세트가 표시됩니다. 마지막으로 반환 된 문자열 배열을 반복하는 방법을 보여줍니다.

Sub Test
    
    Dim textArray() as String

    textArray = Split("Tech on the Net")
    'Result: {"Tech", "on", "the", "Net"}

    textArray = Split("172.23.56.4", ".")
    'Result: {"172", "23", "56", "4"}

    textArray = Split("A;B;C;D", ";")
    'Result: {"A", "B", "C", "D"}

    textArray = Split("A;B;C;D", ";", 1)
    'Result: {"A;B;C;D"}

    textArray = Split("A;B;C;D", ";", 2)
    'Result: {"A", "B;C;D"}

    textArray = Split("A;B;C;D", ";", 3)
    'Result: {"A", "B", "C;D"}

    textArray = Split("A;B;C;D", ";", 4)
    'Result: {"A", "B", "C", "D"}

    'You can iterate over the created array
    Dim counter As Long

    For counter = LBound(textArray) To UBound(textArray)
        Debug.Print textArray(counter)
    Next
 End Sub

배열 요소 반복

For ... 다음

반복자 변수를 인덱스 번호로 사용하는 것은 배열 요소를 반복하는 가장 빠른 방법입니다.

Dim items As Variant
items = Array(0, 1, 2, 3)

Dim index As Integer
For index = LBound(items) To UBound(items)
    'assumes value can be implicitly converted to a String:
    Debug.Print items(index) 
Next

중첩 루프를 사용하여 다차원 배열을 반복 할 수 있습니다.

Dim items(0 To 1, 0 To 1) As Integer
items(0, 0) = 0
items(0, 1) = 1
items(1, 0) = 2
items(1, 1) = 3

Dim outer As Integer
Dim inner As Integer
For outer = LBound(items, 1) To UBound(items, 1)
    For inner = LBound(items, 2) To UBound(items, 2)
        'assumes value can be implicitly converted to a String:
        Debug.Print items(outer, inner)
    Next
Next

각자를 위해 ... 다음

For Each...Next 성능이 중요하지 않은 경우 For Each...Next 루프를 사용하여 배열을 반복 할 수도 있습니다.

Dim items As Variant
items = Array(0, 1, 2, 3)

Dim item As Variant 'must be variant
For Each item In items
    'assumes value can be implicitly converted to a String:
    Debug.Print item
Next

For Each 루프는 모든 차원을 바깥 쪽에서 안쪽으로 반복합니다 (요소가 메모리에 배치 된 순서와 동일 함). 따라서 중첩 루프가 필요하지 않습니다.

Dim items(0 To 1, 0 To 1) As Integer
items(0, 0) = 0
items(1, 0) = 1
items(0, 1) = 2
items(1, 1) = 3

Dim item As Variant 'must be Variant
For Each item In items
    'assumes value can be implicitly converted to a String:
    Debug.Print item
Next

For Each 루프는 성능 문제가있는 경우 Collection 객체를 반복하는 데 가장 잘 사용됩니다.


위의 4 개의 모든 스 니펫은 동일한 출력을 생성합니다.

 0
 1
 2
 3

동적 배열 (배열 크기 조정 및 동적 처리)

동적 배열

배열에 변수를 동적으로 추가 및 축소하는 것은 처리중인 정보에 설정된 수의 변수가 없을 때 큰 이점입니다.

값을 동적으로 추가하기

ReDim 문을 사용하여 배열의 크기를 간단하게 조정할 수 있습니다. 배열의 크기를 조정하지만 이미 배열에 저장된 정보를 유지하려면 Preserve 부분이 필요할 것입니다.

아래 예제에서 우리는 배열을 만들고 이미 배열에있는 값을 유지하면서 각 반복에서 변수를 하나 더 늘립니다.

Dim Dynamic_array As Variant
' first we set Dynamic_array as variant

For n = 1 To 100

    If IsEmpty(Dynamic_array) Then
        'isempty() will check if we need to add the first value to the array or subsequent ones
    
        ReDim Dynamic_array(0)
        'ReDim Dynamic_array(0) will resize the array to one variable only
        Dynamic_array(0) = n

    Else
        ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) + 1)
        'in the line above we resize the array from variable 0 to the UBound() = last variable, plus one effectivelly increeasing the size of the array by one
        Dynamic_array(UBound(Dynamic_array)) = n
        'attribute a value to the last variable of Dynamic_array
    End If

Next

값을 동적으로 제거하기

동일한 논리를 사용하여 배열을 줄일 수 있습니다. 예제에서 "last"값은 배열에서 제거됩니다.

Dim Dynamic_array As Variant
Dynamic_array = Array("first", "middle", "last")
    
ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) - 1)
' Resize Preserve while dropping the last value

배열 재설정 및 동적 재사용

우리가 만든 배열을 다시 활용하여 메모리가 많이 필요하지 않게되어 실행 시간이 느려집니다. 이것은 다양한 크기의 배열에 유용합니다. 배열을 다시 활용하기 위해 사용할 수있는 코드 중 하나는 배열을 (0) 다시 ReDim 하고 배열에 하나의 변수를 지정하고 배열을 다시 자유롭게 늘리는 것입니다.

아래 스 니펫에서는 1에서 40 사이의 값을 가진 배열을 만들고 배열을 비우고 40에서 100까지의 값으로 배열을 다시 채 웁니다.이 모든 작업은 동적으로 수행됩니다.

Dim Dynamic_array As Variant

For n = 1 To 100

    If IsEmpty(Dynamic_array) Then
        ReDim Dynamic_array(0)
        Dynamic_array(0) = n
    
    ElseIf Dynamic_array(0) = "" Then
        'if first variant is empty ( = "") then give it the value of n
        Dynamic_array(0) = n
    Else
        ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) + 1)
        Dynamic_array(UBound(Dynamic_array)) = n
    End If
    If n = 40 Then
        ReDim Dynamic_array(0)
        'Resizing the array back to one variable without Preserving,
        'leaving the first value of the array empty
    End If

Next

들쭉날쭉 한 배열 (배열의 배열)

들쭉날쭉 한 배열 NOT 다차원 배열

배열 배열 (들쭉날쭉 한 배열)은 다차원 배열과 시각적으로 동일하지 않습니다. 다차원 배열은 치수 (요소 배열 내부)에 정의 된 수의 요소가있는 행렬 (직사각형)처럼 보이지만 지그재그 배열은 연간 달력은 내부 배열이 다른 달의 요일과 같은 요소 수가 다릅니다.

지그재그 배열은 중첩 된 레벨로 인해 사용하기에는 지저분하고 까다 롭지 만 유형 안전성이별로 없지만 매우 융통성이 있기 때문에 다양한 유형의 데이터를 매우 쉽게 조작 할 수 있으며 사용하지 않거나 포함하지 않아도됩니다. 빈 요소.

들쭉날쭉 한 배열 만들기

아래의 예에서는 Name과 Numbers에 대한 두 개의 배열을 포함하는 들쭉날쭉 한 배열을 초기화 한 다음 각 배열의 한 요소에 액세스합니다.

Dim OuterArray() As Variant
Dim Names() As Variant
Dim Numbers() As Variant
'arrays are declared variant so we can access attribute any data type to its elements

Names = Array("Person1", "Person2", "Person3")
Numbers = Array("001", "002", "003")

OuterArray = Array(Names, Numbers)
'Directly giving OuterArray an array containing both Names and Numbers arrays inside

Debug.Print OuterArray(0)(1)
Debug.Print OuterArray(1)(1)
'accessing elements inside the jagged by giving the coordenades of the element

들쭉날쭉 한 배열의 동적 생성 및 읽기

우리는 배열을 구성하는 데있어 더 동적 일 수 있습니다. 고객 데이터 시트가 Excel에 있다고 가정하고 고객 세부 정보를 출력하기위한 배열을 만들고 싶습니다.

   Name -   Phone   -  Email  - Customer Number 
Person1 - 153486231 - 1@STACK - 001
Person2 - 153486242 - 2@STACK - 002
Person3 - 153486253 - 3@STACK - 003
Person4 - 153486264 - 4@STACK - 004
Person5 - 153486275 - 5@STACK - 005

우리는 Header 배열과 Customers 배열을 동적으로 만들 것이며, Header에는 열 제목이 포함될 것이며 Customers 배열에는 각 고객 / 행의 정보가 배열로 포함됩니다.

Dim Headers As Variant
' headers array with the top section of the customer data sheet
    For c = 1 To 4
        If IsEmpty(Headers) Then
            ReDim Headers(0)
            Headers(0) = Cells(1, c).Value
        Else
            ReDim Preserve Headers(0 To UBound(Headers) + 1)
            Headers(UBound(Headers)) = Cells(1, c).Value
        End If
    Next
    
Dim Customers As Variant
'Customers array will contain arrays of customer values
Dim Customer_Values As Variant
'Customer_Values will be an array of the customer in its elements (Name-Phone-Email-CustNum)
    
    For r = 2 To 6
    'iterate through the customers/rows
        For c = 1 To 4
        'iterate through the values/columns
            
            'build array containing customer values
            If IsEmpty(Customer_Values) Then
                ReDim Customer_Values(0)
                Customer_Values(0) = Cells(r, c).Value
            ElseIf Customer_Values(0) = "" Then
                Customer_Values(0) = Cells(r, c).Value
            Else
                ReDim Preserve Customer_Values(0 To UBound(Customer_Values) + 1)
                Customer_Values(UBound(Customer_Values)) = Cells(r, c).Value
            End If
        Next
        
        'add customer_values array to Customers Array
        If IsEmpty(Customers) Then
            ReDim Customers(0)
            Customers(0) = Customer_Values
        Else
            ReDim Preserve Customers(0 To UBound(Customers) + 1)
            Customers(UBound(Customers)) = Customer_Values
        End If
        
        'reset Custumer_Values to rebuild a new array if needed
        ReDim Customer_Values(0)
    Next

    Dim Main_Array(0 To 1) As Variant
    'main array will contain both the Headers and Customers
    
    Main_Array(0) = Headers
    Main_Array(1) = Customers

To better understand the way to Dynamically construct a one dimensional array please check Dynamic Arrays (Array Resizing and Dynamic Handling) on the Arrays documentation.

위 스 니펫의 결과는 4 개의 요소, 2 개의 들여 쓰기 레벨을 가진 배열 중 하나와 2 개의 배열을 가진 지그재그 배열입니다. 다른 하나는 각각 4 개의 요소와 3 개의 들여 쓰기 레벨의 5 개의 배열을 포함하는 다른 지그재그 배열입니다. 구조 아래를 참조하십시오.

Main_Array(0) - Headers - Array("Name","Phone","Email","Customer Number")
          (1) - Customers(0) - Array("Person1",153486231,"1@STACK",001)
                Customers(1) - Array("Person2",153486242,"2@STACK",002)
                ...
                Customers(4) - Array("Person5",153486275,"5@STACK",005)

이 정보에 액세스하려면 Jagged Array의 구조를 염두에 두어야합니다. 위의 예제에서 Main Array 에는 Headers Array 및 Array of Array ( Customers )가 포함되어 있으므로 여러 가지 방법으로 볼 수 있습니다. 요소에 액세스합니다.

이제 Main Array 의 정보를 읽고 각 고객 정보를 Info Type: Info 로 인쇄합니다.

For n = 0 To UBound(Main_Array(1))
    'n to iterate from fisrt to last array in Main_Array(1)
    
    For j = 0 To UBound(Main_Array(1)(n))
        'j will iterate from first to last element in each array of Main_Array(1)
        
        Debug.Print Main_Array(0)(j) & ": " & Main_Array(1)(n)(j)
        'print Main_Array(0)(j) which is the header and Main_Array(0)(n)(j) which is the element in the customer array
        'we can call the header with j as the header array has the same structure as the customer array
    Next
Next

고객의 이름에 액세스하기 위해 위의 예에서 Main_Array -> Customers -> CustomerNumber -> Name 에 액세스 Main_Array -> Customers -> CustomerNumber -> Name 3 단계 인 "Person4""Person4" 하면 "Person4" 가 반환됩니다. Main_Array(Customers)(CustomerNumber)(Name) Main_Array(1)(3)(0) , Main_Array(Customers)(CustomerNumber)(Name) 위치, Customers Jagged 배열의 고객 4의 위치 및 마지막으로 필요한 요소의 위치 Main_Array(Customers)(CustomerNumber)(Name) .

다차원 배열

다차원 배열

이름에서 알 수 있듯이 다차원 배열은 둘 이상의 차원 (일반적으로 두 개 또는 세 개)을 포함하지만 최대 32 개의 차원을 포함 할 수있는 배열입니다.

다중 배열은 다양한 수준의 행렬처럼 작동하며 예를 들어 1, 2 및 3 차원 사이의 비교를들 수 있습니다.

One Dimension이 일반적인 배열이며, 요소 목록처럼 보입니다.

Dim 1D(3) as Variant

*1D - Visually*
(0)
(1)
(2)

2 차원은 스도쿠 격자 또는 엑셀 시트처럼 보일 것입니다. 배열을 초기화 할 때 배열에 몇 개의 행과 열이 있어야하는지 정의 할 수 있습니다.

Dim 2D(3,3) as Variant
'this would result in a 3x3 grid 

*2D - Visually*
(0,0) (0,1) (0,2)
(1,0) (1,1) (1,2)
(2,0) (2,1) (2,2)

3 차원은 Rubik의 큐브처럼 보이기 시작합니다. 배열을 초기화 할 때 행과 열, 배열 / 레이어를 정의 할 것입니다.

Dim 3D(3,3,2) as Variant
'this would result in a 3x3x3 grid

*3D - Visually*
       1st layer                 2nd layer                  3rd layer
         front                     middle                     back
(0,0,0) (0,0,1) (0,0,2) ¦ (1,0,0) (1,0,1) (1,0,2) ¦ (2,0,0) (2,0,1) (2,0,2)
(0,1,0) (0,1,1) (0,1,2) ¦ (1,1,0) (1,1,1) (1,1,2) ¦ (2,1,0) (2,1,1) (2,1,2)
(0,2,0) (0,2,1) (0,2,2) ¦ (1,2,0) (1,2,1) (1,2,2) ¦ (2,2,0) (2,2,1) (2,2,2)

더 많은 차원은 3D의 곱셈으로 생각할 수 있으므로 4D (1,3,3,3)는 두 개의 나란히있는 3D 배열이됩니다.


2 차원 배열

생성

아래 예제는 직원 목록을 편집하고 각 직원은 목록 (이름, 성, 주소, 전자 메일, 전화 ...)에 대한 정보 집합을 가지며 예제는 본질적으로 배열에 저장됩니다 직원, 정보)은 (0,0)이 첫 번째 직원의 이름입니다.

Dim Bosses As Variant
'set bosses as Variant, so we can input any data type we want

Bosses = [{"Jonh","Snow","President";"Ygritte","Wild","Vice-President"}]
'initialise a 2D array directly by filling it with information, the redult wil be a array(1,2) size 2x3 = 6 elements

Dim Employees As Variant
'initialize your Employees array as variant
'initialize and ReDim the Employee array so it is a dynamic array instead of a static one, hence treated differently by the VBA Compiler
ReDim Employees(100, 5)
'declaring an 2D array that can store 100 employees with 6 elements of information each, but starts empty
'the array size is 101 x 6 and contains 606 elements

For employee = 0 To UBound(Employees, 1)
'for each employee/row in the array, UBound for 2D arrays, which will get the last element on the array
'needs two parameters 1st the array you which to check and 2nd the dimension, in this case 1 = employee and 2 = information
    For information_e = 0 To UBound(Employees, 2)
    'for each information element/column in the array
        
        Employees(employee, information_e) = InformationNeeded ' InformationNeeded would be the data to fill the array
        'iterating the full array will allow for direct attribution of information into the element coordinates
    Next
Next

크기 조정

Resizing 또는 ReDim Preserve One-Dimension 배열에 대한 표준과 같이 오류가 발생하는 대신 원본과 크기가 같고 추가 할 행 / 열 수를 사용하여 임시 배열로 정보를 전송해야합니다. 아래 예제에서 임시 배열을 초기화하고, 원래 배열에서 정보를 전송하고, 나머지 빈 요소를 채우고, 임시 배열을 원래 배열로 바꾸는 방법을 살펴 보겠습니다.

Dim TempEmp As Variant
'initialise your temp array as variant
ReDim TempEmp(UBound(Employees, 1) + 1, UBound(Employees, 2))
'ReDim/Resize Temp array as a 2D array with size UBound(Employees)+1 = (last element in Employees 1st dimension) + 1,
'the 2nd dimension remains the same as the original array. we effectively add 1 row in the Employee array

'transfer
For emp = LBound(Employees, 1) To UBound(Employees, 1)
    For info = LBound(Employees, 2) To UBound(Employees, 2)
        'to transfer Employees into TempEmp we iterate both arrays and fill TempEmp with the corresponding element value in Employees
        TempEmp(emp, info) = Employees(emp, info)
    
    Next
Next

'fill remaining
'after the transfers the Temp array still has unused elements at the end, being that it was increased
'to fill the remaining elements iterate from the last "row" with values to the last row in the array
'in this case the last row in Temp will be the size of the Employees array rows + 1, as the last row of Employees array is already filled in the TempArray

For emp = UBound(Employees, 1) + 1 To UBound(TempEmp, 1)
    For info = LBound(TempEmp, 2) To UBound(TempEmp, 2)
        
        TempEmp(emp, info) = InformationNeeded & "NewRow"
    
    Next
Next

'erase Employees, attribute Temp array to Employees and erase Temp array
Erase Employees
Employees = TempEmp
Erase TempEmp

요소 값 변경

특정 요소의 값을 변경 / 변경하려면 좌표를 변경하여 새로운 값을 지정하기 만하면됩니다. Employees(0, 0) = "NewValue"

또는 좌표 사용 조건을 반복하여 필요한 매개 변수에 해당하는 값을 일치시킵니다.

For emp = 0 To UBound(Employees)
    If Employees(emp, 0) = "Gloria" And Employees(emp, 1) = "Stephan" Then
    'if value found
        Employees(emp, 1) = "Married, Last Name Change"
        Exit For
        'don't iterate through a full array unless necessary
    End If
Next

독서

배열의 요소에 액세스하려면 중첩 루프 (모든 요소를 ​​반복), 루프 및 좌표 (행을 반복하고 열을 직접 액세스) 또는 두 좌표를 모두 사용하여 직접 액세스 할 수 있습니다.

'nested loop, will iterate through all elements
For emp = LBound(Employees, 1) To UBound(Employees, 1)
    For info = LBound(Employees, 2) To UBound(Employees, 2)
        Debug.Print Employees(emp, info)
    Next
Next

'loop and coordinate, iteration through all rows and in each row accessing all columns directly
For emp = LBound(Employees, 1) To UBound(Employees, 1)
    Debug.Print Employees(emp, 0)
    Debug.Print Employees(emp, 1)
    Debug.Print Employees(emp, 2)
    Debug.Print Employees(emp, 3)
    Debug.Print Employees(emp, 4)
    Debug.Print Employees(emp, 5)
Next

'directly accessing element with coordinates
Debug.Print Employees(5, 5)

다차원 배열을 사용할 때 항상 배열 맵을 유지하는 것이 편리하다는 것을 기억하십시오 . 쉽게 다차원이 될 수 있습니다.


3 차원 배열

3D 배열의 경우 2D 배열과 동일한 전제를 사용하며 직원 및 정보를 저장하는 것은 물론 빌딩에서 작업하는 것을 추가합니다.

3D 배열은 종업원 (열로 생각할 수 있음), 정보 (열) 및 건물을 가지며 Excel 문서에서 서로 다른 시트로 생각할 수 있으며 크기는 동일하지만 모든 시트마다 해당 셀 / 요소에 다른 정보 집합. 3D 배열에는 n 개의 2D 배열이 포함됩니다.

생성

3D 배열은 초기화 할 좌표가 필요합니다. Dim 3Darray(2,5,5) As Variant 배열의 첫 번째 좌표는 Building / Sheets (행과 열의 다른 세트) 수이고, 두 번째 좌표는 행과 세 번째를 정의합니다 열. 위의 Dim 하면 108 개의 요소 ( 3*6*6 )로 된 3D 배열이 만들어지며 3 개의 서로 다른 2D 배열 세트를 효과적으로 갖게됩니다.

Dim ThreeDArray As Variant
'initialise your ThreeDArray array as variant
ReDim ThreeDArray(1, 50, 5)
'declaring an 3D array that can store two sets of 51 employees with 6 elements of information each, but starts empty
'the array size is 2 x 51 x 6 and contains 612 elements

For building = 0 To UBound(ThreeDArray, 1)
    'for each building/set in the array
    For employee = 0 To UBound(ThreeDArray, 2)
    'for each employee/row in the array
        For information_e = 0 To UBound(ThreeDArray, 3)
        'for each information element/column in the array
            
            ThreeDArray(building, employee, information_e) = InformationNeeded ' InformationNeeded would be the data to fill the array
        'iterating the full array will allow for direct attribution of information into the element coordinates
        Next
    Next
Next

크기 조정

3D 배열의 크기를 조정하는 것은 2D 크기를 변경하는 것과 비슷합니다. 원래 크기와 동일한 크기의 임시 배열을 만들면 매개 변수의 좌표에 하나를 늘리면 첫 번째 좌표가 배열의 집합 수를 늘리고 둘째는 세 번째 좌표는 각 집합의 행 또는 열 수를 늘립니다.

아래 예제는 각 집합의 행 수를 하나씩 늘리고 최근에 추가 한 요소를 새로운 정보로 채 웁니다.

Dim TempEmp As Variant
'initialise your temp array as variant
ReDim TempEmp(UBound(ThreeDArray, 1), UBound(ThreeDArray, 2) + 1, UBound(ThreeDArray, 3))
'ReDim/Resize Temp array as a 3D array with size UBound(ThreeDArray)+1 = (last element in Employees 2nd dimension) + 1,
'the other dimension remains the same as the original array. we effectively add 1 row in the for each set of the 3D array

'transfer
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
    For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
        For info = LBound(ThreeDArray, 3) To UBound(ThreeDArray, 3)
            'to transfer ThreeDArray into TempEmp by iterating all sets in the 3D array and fill TempEmp with the corresponding element value in each set of each row
            TempEmp(building, emp, info) = ThreeDArray(building, emp, info)
        
        Next
    Next
Next

'fill remaining
'to fill the remaining elements we need to iterate from the last "row" with values to the last row in the array in each set, remember that the first empty element is the original array Ubound() plus 1
For building = LBound(TempEmp, 1) To UBound(TempEmp, 1)
    For emp = UBound(ThreeDArray, 2) + 1 To UBound(TempEmp, 2)
        For info = LBound(TempEmp, 3) To UBound(TempEmp, 3)
            
            TempEmp(building, emp, info) = InformationNeeded & "NewRow"
        
        Next
    Next
Next

'erase Employees, attribute Temp array to Employees and erase Temp array
Erase ThreeDArray
ThreeDArray = TempEmp
Erase TempEmp

요소 값 변경 및 읽기

3D 배열의 요소를 읽고 변경하는 방법은 2D 배열을 수행하는 방법과 비슷하게 수행 할 수 있습니다. 루프 및 좌표의 추가 레벨을 조정하면됩니다.

Do
' using Do ... While for early exit
    For building = 0 To UBound(ThreeDArray, 1)
        For emp = 0 To UBound(ThreeDArray, 2)
            If ThreeDArray(building, emp, 0) = "Gloria" And ThreeDArray(building, emp, 1) = "Stephan" Then
            'if value found
                ThreeDArray(building, emp, 1) = "Married, Last Name Change"
                Exit Do
                'don't iterate through all the array unless necessary
            End If
        Next
    Next
Loop While False

'nested loop, will iterate through all elements
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
    For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
        For info = LBound(ThreeDArray, 3) To UBound(ThreeDArray, 3)
            Debug.Print ThreeDArray(building, emp, info)
        Next
    Next
Next

'loop and coordinate, will iterate through all set of rows and ask for the row plus the value we choose for the columns
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
    For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
        Debug.Print ThreeDArray(building, emp, 0)
        Debug.Print ThreeDArray(building, emp, 1)
        Debug.Print ThreeDArray(building, emp, 2)
        Debug.Print ThreeDArray(building, emp, 3)
        Debug.Print ThreeDArray(building, emp, 4)
        Debug.Print ThreeDArray(building, emp, 5)
    Next
Next

'directly accessing element with coordinates
Debug.Print Employees(0, 5, 5)


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow