vba Pattern of numbers using for next.

montecarlo2012

Well-known Member
Joined
Jan 26, 2011
Messages
985
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

Easy bullets in Excel
If you have a numeric keypad, press Alt+7 on numeric keypad to type a bullet in Excel.
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,223,713
Messages
6,174,038
Members
452,542
Latest member
Bricklin

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