Search code examples
excelrangecellvba

Excel VBA How to select variable range of cells


I tried to search this problem but found no similar issue.

I am still newbie in VBA and I'm trying to create macro which chooses range of cells depending on the user's input and then creates an outlined grid out of those selected cells.

I have two ActiveX buttons in my Excel workbook which let the user to input how big the grid is they want to use (Width & Height). I am struggling to include the above mentioned width and height to my code. Here is the code for the buttons (nothing unclear about them):

Private Sub Height_Click()
Dim Height As Integer
Height = InputBox("Syötä ruudukon korkeus", "Ruudukon korkeus", "Syötä tähän")
Range("E5") = Height
End Sub

And width button:

Private Sub Width_Click()
Dim Width As Integer
Width = InputBox("Syötä ruudukon leveys", "Ruudukon leveys", "Syötä tähän")
Range("E2") = Width
End Sub

I want my grid to start from cell "G2" and expand right&down from there and change the size of the selected cells. However the code I have written isn't working at all (as I thought). Here is the code:

Private Sub CreateGrid_Click()
Columns("G:G+E2").Select
    Selection.ColumnWidth = 1
Rows("2:2+E5").Select
    Selection.RowHeight = 1
End Sub

Cells "E2" and "E5" have the values of width and height printed, respectively. Nothing happens when I click the CreateGrid-button. Any ideas how I can make this code work? Thanks a lot for all answers.

-Teemu


Solution

  • EDIT:

    Private Sub CreateGrid_Click()
    Range("G2:" & Range("G2").Offset(Range("E5").Value,Range("E2").Value).Addresslocal).Select
    End Sub
    

    If this doesn't do what you expect, please let me know and I will try to help correct it.