将1维数组编写到单个列

时间:2016-07-28 23:36:57

标签: arrays excel vba excel-vba

Sub Lottery()
Dim A As Long
Dim B As Long
Dim C As Long
Dim D As Long
Dim E As Long
Dim N As Long
Dim xLot() As String

N = 0
ReDim xLot(1 To 169911)
For A = 1 To 27
    For B = A + 1 To 28
        For C = B + 1 To 29
            For D = C + 1 To 30
                For E = D + 1 To 31
                    N = N + 1

                    xLot(N) = A & "-" & B & "-" & C & "-" & D & "-" & E
                    'Debug.Print xLot(N), N
                    'Range("a" & N).Value = xLot(N)

                Next E
            Next D
        Next C
    Next B
Next A

Range("A1:A169911").Resize(169911, 1).Value = Application.WorksheetFunction.Transpose(xLot)

End Sub

使用转置运行时错误13类型不匹配。我在另一篇博客中读到,我写不到超过65535个单元格。在另一个例子中,在行38840到169911(组合的数量)之后,单元具有#N / A.我已经在即时窗口中运行它,并且所有组合都使用了数组帐户。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:4)

您不能将转置函数用于超过65535个值,因为转置会将一系列列转换为一系列行(反之亦然),并且excel工作表中只能有65535列。您可以通过为数组提供第二个维度来绕过转置函数,因此将redim语句更改为:

ReDim xLot(1 To 169911,0)

和你的任务陈述:

xLot(N,0) = A & "-" & B & "-" & C & "-" & D & "-" & E

...最后你的范围声明:

Range("A1:A169911").Resize(169911, 1).Value = xLot

编辑:刚刚测试过,这段代码对我有用:

Sub Lottery()
    Dim A As Long
    Dim B As Long
    Dim C As Long
    Dim D As Long
    Dim E As Long
    Dim N As Long
    Dim xLot() As String

    N = 0
    ReDim xLot(1 To 169911, 0)
    For A = 1 To 27
        For B = A + 1 To 28
            For C = B + 1 To 29
                For D = C + 1 To 30
                    For E = D + 1 To 31
                        N = N + 1

                        xLot(N, 0) = A & "-" & B & "-" & C & "-" & D & "-" & E
                        'Debug.Print xLot(N), N
                        'Range("a" & N).Value = xLot(N)

                    Next E
                Next D
            Next C
        Next B
    Next A

    Range("A1:A169911").Resize(169911, 1).Value = xLot
End Sub

答案 1 :(得分:2)

Transpose的上限约为65k项。

如果您改为

ReDim xLot(1 To 169911, 1 to 1) 
'....
xLot(N, 1) = A & "-" & B & "-" & C & "-" & D & "-" & E
'...

然后你不需要Transpose:

Range("A1:A169911").Value = xLot