You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VBA循环中动态向数组添加指定工作表名称

解决VBA动态数组添加工作表名称及遍历问题

问题根源

你用的是VBA普通动态数组,这类数组没有Add方法,直接调用会报错。得通过ReDim Preserve动态扩容数组,再逐个赋值。

修改后的代码(生成目标工作表名称数组)

' 创建目标工作表名称数组
Dim sheets_names_array() As Variant
Dim ws As Worksheet
Dim arrIndex As Integer

arrIndex = 0 ' 初始化数组索引,从0开始

For Each ws In ThisWorkbook.Worksheets
    Select Case ws.Name
        ' 跳过不需要的工作表,多个Case可合并书写
        Case "Qlik Ingestion", "Dropdown Values", "VBmacro"
        Case Else
            ' 动态扩容数组,Preserve参数保留已有数据
            ReDim Preserve sheets_names_array(arrIndex)
            ' 将当前工作表名称存入数组对应索引位置
            sheets_names_array(arrIndex) = ws.Name
            arrIndex = arrIndex + 1 ' 索引自增,准备存储下一个元素
    End Select
Next ws

遍历数组的两种方式

1. 按索引遍历(适合需要获取元素位置的场景)

' 先判断数组是否有元素,避免空数组遍历报错
If arrIndex > 0 Then
    Dim i As Integer
    For i = LBound(sheets_names_array) To UBound(sheets_names_array)
        ' 示例:在立即窗口打印工作表名称,可替换为你的业务逻辑
        Debug.Print "工作表名称:" & sheets_names_array(i)
    Next i
End If

2. For Each遍历(更简洁,无需关注索引)

' 先判断数组非空
If arrIndex > 0 Then
    Dim sheetName As Variant
    For Each sheetName In sheets_names_array
        Debug.Print "工作表名称:" & sheetName
        ' 这里添加你的处理逻辑
    Next sheetName
End If

关键说明

  • ReDim Preserve:每次扩容只能修改数组最后一维的大小,必须加Preserve参数,否则之前存入的数据会被清空。
  • 计数器arrIndex:跟踪当前要存储的数组位置,确保每个符合条件的工作表名称存入正确索引。
  • 非空判断:如果所有工作表都被跳过,数组会处于未初始化状态,直接遍历会触发错误,因此需要先判断arrIndex > 0。

内容的提问来源于stack exchange,提问作者Electra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 05:05:23