VBA Excel单元格组合脚本1004错误

时间:2016-08-23 13:36:07

标签: excel vba excel-vba

该脚本应该将每组单元格的两组四列组合并在相邻单元格上打印每个组合。我有两套三个细胞,但现在我得到了一个

  

1004应用程序定义或对象定义的erorr

它强调:

Set out_1 = Range("I1", Range("L1").Offset(UBound(c1) * UBound(c2) * UBound(c3) * UBound(c7)))

我不确定如何解决这个问题,有人可以帮忙吗?

Sub Combinations()

Dim c1() As Variant
Dim c2() As Variant
Dim c3() As Variant
Dim c4() As Variant
Dim c5() As Variant
Dim c6() As Variant
Dim c7() As Variant
Dim c8() As Variant
Dim out1() As Variant
Dim out2() As Variant
Dim j, k, l, m, n As Long

Dim col1 As Range
Dim col2 As Range
Dim col3 As Range
Dim col4 As Range
Dim col5 As Range
Dim col6 As Range
Dim col7 As Range
Dim col8 As Range
Dim out_1 As Range
Dim out_2 As Range

Set col1 = Range("A1", Range("A1").End(xlDown))
Set col2 = Range("C1", Range("C1").End(xlDown))
Set col3 = Range("E1", Range("E1").End(xlDown))
Set col4 = Range("B1", Range("B1").End(xlDown))
Set col5 = Range("D1", Range("D1").End(xlDown))
Set col6 = Range("F1", Range("F1").End(xlDown))
Set col7 = Range("G1", Range("G1").End(xlDown))
Set col8 = Range("H1", Range("H1").End(xlDown))

c1 = col1
c2 = col2
c3 = col3
c4 = col4
c5 = col5
c6 = col6
c7 = col7
c8 = col8

Set out_1 = Range("I1", Range("L1").Offset(UBound(c1) * UBound(c2) * UBound(c3) * UBound(c7)))
Set out_2 = Range("M1", Range("P1").Offset(UBound(c4) * UBound(c5) * UBound(c6) * UBound(c8)))
out1 = out_1
out2 = out_2

j = 1
k = 1
l = 1
m = 1
n = 1

Do While j <= UBound(c1)
    Do While k <= UBound(c2)
        Do While l <= UBound(c3)
            Do While m <= UBound(c7)
                out1(n, 1) = c1(j, 1)
                out1(n, 2) = c2(k, 1)
                out1(n, 3) = c3(l, 1)
                out1(n, 4) = c7(m, 1)
                n = n + 1
                m = m + 1
            Loop
            m = m
            l = l + 1
        Loop
        l = 1
        k = k + 1
    Loop
    k = 1
    j = j + 1
Loop

j = 1
k = 1
l = 1
m = 1
n = 1


Do While j <= UBound(c4)
    Do While k <= UBound(c5)
        Do While l <= UBound(c6)
            Do While m <= UBound(c8)
                out1(n, 1) = c1(j, 1)
                out1(n, 2) = c2(k, 1)
                out1(n, 3) = c3(l, 1)
                out1(n, 4) = c8(m, 1)
                n = n + 1
                m = m + 1
            Loop
            m = m
            l = l + 1
        Loop
        l = 1
        k = k + 1
    Loop
    k = 1
    j = j + 1
Loop

out_1.Value = out1
out_2.Value = out2
End Sub

1 个答案:

答案 0 :(得分:1)

考虑@ ScottCraner的评论。

此外,即使您确定所有列都至少有一个非空单元格,如果这是第1行,那么xlDown方法会使Ubound()返回100万!

在这种情况下替换:

Set col1 = Range("A1", Range("A1").End(xlDown))
Set col2 = Range("C1", Range("C1").End(xlDown))
...

with:

Set col1 = Range("A1", Cells(Rows.Count, 1).End(xlUp))
Set col2 = Range("C1", Cells(Rows.Count, 3).End(xlUp)) '<--keep numeric column index in "Cells(Rows.Count,...)" synchronized with string column index in Range("...1")
...