简体   繁体   中英

How to define range for next loop in VBA

I'm a newbie and I'm trying to learn VBA (Sorry for any mistake in English, I'm not a native speaker). I am trying to solve the following assignment: "Create a procedure that outputs the multiplication table values from 11 to 20 in Excel as shown below:"

multiplication table

This is my code:

Sub einmaleins()
Dim x As Integer, y As Integer
For x = 11 To 20
For y = 11 To 20
Cells(x, y) = x * y
Next
Next
End Sub

It works but puts the table from K11 to S20. I need it to enter the values from A1 to J10 I have tried

*Range("A1:J10").FormulaR1C1 = "=ROW(RC)*COLUMN(RC)"* 

but it doesn´t work.

Help is greatly appreciated

In fact your formula approach is better as avoids a loop.

Range("A1:J10").FormulaR1C1 = "=(ROW(RC)+10)*(COLUMN(RC)+10)"

You can subtract 10 from each x and y coordinate.

For example, x = 11 and y = 11 would give cells(1, 1) .

Sub einmaleins()
    Dim x As Integer, y As Integer

    For x = 11 To 20
        For y = 11 To 20
            Cells(x - 10, y - 10) = x * y
        Next
    Next
End Sub

Here you go if you want more control over the code and if you plan to use this repeatedly. It will not matter even if it is 11- 20 or any other number.

Also recommend that you refer the cell with the sheet reference so that when you go on you will have no issue with referencing. EG: Sheet1.Cells (y,x)

Here you go - The function.

Function einmaleins(fNumber As Integer, lNumber As Integer) As Integer

    Dim x, y As Integer

    For x = fNumber To lNumber

        For y = fNumber To lNumber
                Sheet1.Cells(x - (fNumber - 1), y - (fNumber - 1)) = x * y
        Next
    Next

    End Function

//Call the function

Sub multiTable()
 Call einmaleins(11, 20)
End Sub

Hope this helps

Tschüss

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM