VBA Application/object 将数组输出到 .Cell 声明范围时定义错误

VBA Application/object defined error when outputting array to .Cell declared range

我在尝试将数组输出到某个范围时遇到 'application-defined or object defined error' 的问题。

 Worksheets("Log").Range(.Cells(MnthCount + 4, 6), .Cells(MnthCount + 4, MnthDayCount + 5)) = FrstLtr

也就是代码,数组FrstLtr长度为31个值。 MnthCount是2,MnthDayCount是31,范围内应该有足够的space来输出数组吧?这里有什么问题?

将数组值复制到工作表

快速修复

With Worksheets("Log")
    .Range(.Cells(MnthCount + 4, 6), _
        .Cells(MnthCount + 4, MnthDayCount + 5)).Value = FrstLtr
End With

了解这个

Dim cCount As Long
cCount = (MnthDayCount + 5) - (6) + (1) ' 5 - 6 + 1 = 0
cCount = MnthDayCount

调整大小连接

Worksheets("Log").Cells(MnthCount + 4, 6).Resize(, MnthDayCount).Value = FrstLtr
Worksheets("Log").Cells(MnthCount + 4, 6).Resize(, cCount).Value = FrstLtr

数组大小调整

With Worksheets("Log").Cells(MnthCount + 4, 6)
    .Resize(, UBound(FstrLtr) + 1).Value = FrstLtr ' 1D zero-based
    .Resize(, UBound(FstrLtr)).Value = FrstLtr ' 1D one-based
    .Resize(, UBound(FstrLtr, 2) + 1).Value = FrstLtr ' 2D zero-based
    .Resize(, UBound(FstrLtr, 2)).Value = FrstLtr ' 2D one-based
End With

常见场景

Dim wb As Workbook: Set wb = ThisWorkbook

Dim dws As Worksheet: Set dws = wb.Worksheets("Log")

With dws.Cells(MnthCount + 4, 6)
    .Resize(, cCount).Value = FrstLtr
End With