在VBA中编辑数组

时间:2018-01-02 22:34:01

标签: arrays vba excel-vba excel

我试图通过数组捕获一个表,并多次遍历该数组,在每次迭代中更改两列中的数据。我当前的代码(下面)设置为迭代数组一次,将数据分为两部分(,5)和(,6)。不幸的是,它显示错误读取

  

运行时错误'9':下标超出范围

Sub arraytest()

Dim myArray As Variant

myArray = ActiveWorkbook.Worksheets("Semesters").ListObjects("tblSemester").DataBodyRange.Value

Dim i As Integer
Dim Roww As Integer

Roww = 1

While i < 10
    For Each r In myArray
        myArray(i, 5) = "18/19"
        myArray(i, 6) = "Fall"
        Roww = Roww + 1
        i = 10
    Next
Wend


Worksheets("Sheet1").Range("A2", "U2").Resize(UBound(myArray, 1)).Value = myArray

End Sub

如何编辑代码以成功遍历数组,更改特定列上的数据?

1 个答案:

答案 0 :(得分:0)

我想你想要这个:

MariaDB [_]> DROP TABLE IF EXISTS `table_name`;
Query OK, 0 rows affected (0.00 sec)

MariaDB [_]> CREATE TABLE IF NOT EXISTS `table_name` (
    ->   `id` SERIAL,
    ->   `class` JSON NOT NULL,
    ->   CHECK (JSON_VALID(`class`))
    -> );
Query OK, 0 rows affected (0.00 sec)

MariaDB [_]> INSERT INTO `table_name` (`class`)
    -> VALUES ('{"class": 1, "student": [{"student_id": "10", "name": "A"}, {"student_id": "5", "name": "B"}]}');
Query OK, 1 row affected (0.00 sec)

MariaDB [_]> SELECT `id`, `class`
    -> FROM `table_name`;
+----+------------------------------------------------------------------------------------------------+
| id | class                                                                                          |
+----+------------------------------------------------------------------------------------------------+
|  1 | {"class": 1, "student": [{"student_id": "10", "name": "A"}, {"student_id": "5", "name": "B"}]} |
+----+------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

MariaDB [_]> UPDATE `table_name`
    -> SET `class` = 
    ->   JSON_SET(
    ->     `class`,
    ->     REPLACE(
    ->       JSON_UNQUOTE(
    ->         JSON_SEARCH(`class`,
    ->                     'one',
    ->                     5,
    ->                     NULL,
    ->                     '$.student'
    ->                    )
    ->       ),
    ->     'student_id',
    ->     'name'
    ->     ),
    ->     'bbb'
    ->   )
    -> WHERE `id` = 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [_]> SELECT `id`, `class`
    -> FROM `table_name`;
+----+--------------------------------------------------------------------------------------------------+
| id | class                                                                                            |
+----+--------------------------------------------------------------------------------------------------+
|  1 | {"class": 1, "student": [{"student_id": "10", "name": "A"}, {"student_id": "5", "name": "bbb"}]} |
+----+--------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)