Paulo Silveira Xpto
New Member
- Joined
- Aug 27, 2020
- Messages
- 11
- Office Version
- 2016
- Platform
- Windows
HELLO, I HAVE A VBA CODE THAT WORKS WITH UP TO 32 NUMBERS UNDER COMBINATORY ANALYSIS. IT FILLS AN EXCEL COLUMN WITH 906,192 LINES. IF I CHOOSE MORE THAN 32 NUMBER THERE IS AN ERROR, BECAUSE THE EXCEL LIMIT OF LINES OVERFLOWS. I NEED HELP CREATING NEW COLUMNS, SOMETHING LIKE THIS, I REACHED LINE 1,000,000 NEW COLUMNS ARE CREATED AND THE SEQUENCE CONTINUES.
THE CODE IS BELOW
THE CODE IS BELOW
VBA Code:
Option Explicit
Private aResult As ListObject 'Tabela de resultados
Private aValor As ListObject 'Tabela de valores a combinar
Private aListRowIndex As Long 'Linha da tabela de resultados
Private aNumElements As Long 'Quantidade de valores a combinar disponíveis
Private aNumCols As Long 'Quantidade de elementos em cada grupo de combinação
Private aNumRows As Long 'Quantidade de resultados gerados
Private Sub Main()
Dim Elements As Variant 'Elementos disponíveis para combinar
Dim Result As Variant 'Set de resultados de cada iteração
'Inicialização de variáveis
Set aResult = Me.ListObjects("loResult")
Set aValor = Me.ListObjects("loValor")
Elements = WorksheetFunction.Transpose(aValor.DataBodyRange)
aNumElements = UBound(Elements)
aNumCols = Me.Range("TamanhoGrupo")
'Validação
If aNumCols > aNumElements Then
MsgBox "A quantidade de repetições deve ser menor ou igual à quantidade de valores disponíveis.", vbInformation
GoTo Quit
End If
aNumRows = WorksheetFunction.Combin(aNumElements, aNumCols)
ReDim Result(1 To aNumCols)
aListRowIndex = 1
'Formatar tabela de resultados
FormatTable
'Inicia a recursão para gerar as combinações
Combinar Elements, aNumCols, Result, 1, 1
Quit:
End Sub
Sub Combinar(ByVal Elements As Variant, _
ByVal p As Long, _
ByVal Result As Variant, _
ByVal iElement As Integer, _
ByVal iIndex As Integer)
Static iEvents As Long 'Para desafogar temporariamente processos pendentes do Excel
Dim i As Long
iEvents = iEvents + 1
If iEvents Mod 100 = 0 Then DoEvents
For i = iElement To aNumElements
Result(iIndex) = Elements(i)
If iIndex = p Then
aResult.ListColumns(1).DataBodyRange(aListRowIndex).Resize(, p) = Result
aListRowIndex = aListRowIndex + 1
Else
Combinar Elements, p, Result, i + 1, iIndex + 1
'Se quiser que seja calculado um Arranjo ao invés da Combinação,
'comente a expressão acima e use a expressão abaixo:
'Combinar Elements, p, Result, i, iIndex + 1
End If
Next i
End Sub
Private Sub FormatTable()
Dim iCol As Long
With aResult
If .ListColumns.Count > 1 Then
.ListColumns(2).Range.Resize(, .ListColumns.Count - 1).Delete
End If
If .ListRows.Count > 0 Then .DataBodyRange.ClearContents
.Resize .Range.Resize(1 + aNumRows, aNumCols)
For iCol = 1 To .ListColumns.Count
.HeaderRowRange(iCol) = "Col" & iCol
Next iCol
End With
End Sub