应用程序定义的或对象定义的错误Ubound

时间:2018-02-09 07:44:55

标签: excel vba excel-vba

我有一个excel VBA代码,它按月从外部文件中检索记录,并根据列标题进行设置。

但是,我在行.Range("A6").Resize(n, 23) = b中的应用程序定义或对象定义错误中出错

有谁知道为什么

代码:

Sub zz()
Dim arr, c, b(), n&
Application.ScreenUpdating = False
Worksheets("Sheet2").Range("A6").AutoFilter
Workbooks.Open "C:\Users\sophia.tan\Desktop\MasterPlanData.xlsx", 0, 1
arr = Sheets("Excel").UsedRange
ActiveWorkbook.Close 0
c = Array(0, 2, 13, 14, 7, 8, 11, 1, 9, 10, 16, 17, 20, 22, 15, 30, 27, 28, 29, 3, 4, 30)
d = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23)
ReDim b(1 To UBound(arr), 1 To 23)

For i = 2 To UBound(arr)
    If arr(i, 12) >= DateSerial(Year:=2017, Month:=11, Day:=1) And arr(i, 12) <= DateSerial(Year:=2017, Month:=11, Day:=31) Then
        n = n + 1
        For j = 1 To UBound(c)
            b(n, d(j)) = arr(i, c(j))
        Next
    End If
Next


With Worksheets("Sheet2")

    .Range("A6:T" & Rows.Count).CurrentRegion.AutoFilter field:=1, Criteria1:="<>OFM"
    .Range("A6:T" & Rows.Count).CurrentRegion.SpecialCells(xlCellTypeVisible).AutoFilter field:=13, Criteria1:="<>Collar & Cuff"
    .Range("A6:T" & Rows.Count).CurrentRegion.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    .Range("A6").Resize(n, 23) = b
    .Range("A6").CurrentRegion.Sort key1:=Range("G6"), order1:=xlAscending, Header:=xlYes
    .Range("A6").Select


End With

Application.ScreenUpdating = 1

End Sub

2 个答案:

答案 0 :(得分:3)

您对 n 的决定对于If语句是主观的。但是,&#39;行中的任何未填充值 b 将是vbnullstrings,并将生成真正的空白单元格。

.Range("A6").Resize(ubound(b, 1), ubound(b, 2)) = b

可替换地,

For i = 2 To UBound(arr)
    If arr(i, 12) >= DateSerial(Year:=2017, Month:=11, Day:=1) And arr(i, 12) <= DateSerial(Year:=2017, Month:=11, Day:=31) Then
        n = n + 1
        For j = 1 To UBound(c)
            b(n, d(j)) = arr(i, c(j))
        Next
    End If
Next
b = application.transpose(b)
redim preserve b(lbound(b, 1) to ubound(b, 1), lbound(b, 2) to n)
b = application.transpose(b)
.Range("A6").Resize(n, 23) = b

使用保留参数时,您只能使用ReDim调整数组的最后一个等级。

答案 1 :(得分:0)

尝试

.Range("A6").Resize(n, 23).Value = b