vba Pattern of numbers using for next.

montecarlo2012

Well-known Member
Joined
Jan 26, 2011
Messages
984
Office Version
  1. 2010
Platform
  1. Windows
Hello people.
VBA Code:
Sub April_16()
   For i = 1 To 5
         For j = 1 To i
               Cells(i, j).Value = j
               
                  For k = i + 1 To j
                            Cells(i, j).Value = 1
                       
                  Next
         Next
   Next
End Sub
with this code the output is:
1618557509335.png

It is not, what I expected
This is what is
my goal
1618557613420.png

Thank you for reading this
Please, anyone give me a hand here.
 

Excel Facts

Create a chart in one keystroke
Select the data and press Alt+F1 to insert a default chart. You can change the default chart to any chart type
Hi, maybe..

VBA Code:
Sub April_16()
Dim i As Long, j As Long
For i = 1 To 5
    For j = 1 To 5
          Cells(i, j).Value = IIf(j > i, 1, j)
    Next j
Next i
End Sub
 
Upvote 0
Solution
Hi, as it can be achieved without looping … Anyway for the looping fun :​
VBA Code:
Sub Demo1()
  Const D = ","
    For C% = 1 To 5
        [A:E].Rows(C).Value2 = Split(Join(Evaluate("COLUMN(" & Cells(1).Resize(, C).Address & ")"), D) & Application.Rept(D & "1", 5 - C), D)
    Next
End Sub
 
Last edited by a moderator:
Upvote 0
Not a concern here with such few columns but with big data the smart way is to use an array variable​
in order to just write data at once rather than cell by cell aka columns # * columns # (here 5 * 5 = 25 times but imagine for 16 384 columns !)​
and obviouly smarter using zero rather than one :​
VBA Code:
Sub Demo2()
    Dim R%, C%, N%(1 To 5, 1 To 5)
    For R = 1 To 5
    For C = 1 To R
        N(R, C) = C
    Next C, R
    [A1:E5].Value2 = N
End Sub
 
Upvote 0

Forum statistics

Threads
1,216,101
Messages
6,128,843
Members
449,471
Latest member
lachbee

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top