为什么VBA数组直接赋值给单元格区域为空,指定索引时却能正常输出
问题核心原因及修复方案
核心错误点
- 数组下标默认从0起始,你定义的数组行维度有两行,写入区域时VBA取了全空的第一行
- Range内的Cells对象未指定父工作表,活动表非Test时会出现范围异常
- dtcols列数计算错误,会导致你少取原数组的两列内容
具体修复说明
1. 数组维度修正
VBA默认数组下标从0开始,你写ReDim titlearray(1, totalcols)实际生成了2行(下标0、1)、totalcols+1列(下标0~totalcols)的数组:
- 你仅对下标为1的行赋值,下标为0的行全为空值
- 赋值给单行区域时,VBA默认取数组第一行(下标0)写入,所以得到空白单元格
修复方法:定义数组时明确指定下标上下限,确保是1行N列的结构:
ReDim titlearray(1 To 1, 1 To totalcols)
如果想全局用1起始下标,可以在模块最顶部加Option Base 1语句。
2. 单元格引用修正
Range内的Cells必须和Range所属工作表一致,避免跨表引用错误,用With块统一父对象:
With Sheets("Test") .Range(.Cells(1, 1), .Cells(1, totalcols)) = titlearray End With
3. dtcols计算修正
原计算逻辑会少算2列,正确的数组列数计算方式为:
dtcols = UBound(dtarray, 2) - LBound(dtarray, 2) + 1
修正后完整代码
Sub GenerateList() Dim baseyr As Long, mnthct As Long, mnthyr As String Dim yr As Long, mnthcols As Long, dtarray As Variant Dim dtcols As Long, totalcols As Long, i As Long Dim titlearray As Variant baseyr = 2019 mnthct = 1 mnthyr = InputBox("Actuals up to: (xx/xxxx format)") Sheets("Parameters").Cells(4, 2) = mnthyr yr = Right(mnthyr, 4) mnthcols = 12 * (yr - baseyr + 2) dtarray = Sheet3.Cells(1, 1).CurrentRegion ' 修正列数计算 dtcols = UBound(dtarray, 2) - LBound(dtarray, 2) + 1 totalcols = dtcols + mnthcols ' 修正数组定义,明确1行N列 ReDim titlearray(1 To 1, 1 To totalcols) For i = 1 To totalcols If i <= dtcols Then titlearray(1, i) = dtarray(1, i) Else titlearray(1, i) = mnthct & "/1/" & baseyr mnthct = mnthct + 1 If mnthct = 13 Then baseyr = baseyr + 1 mnthct = 1 End If End If Next ' 修正单元格引用,统一父对象 With Sheets("Test") .Range(.Cells(1, 1), .Cells(1, totalcols)) = titlearray End With End Sub
内容的提问来源于stack exchange,提问作者Jusec
相关产品推荐
相关产品推荐

