Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA does not place button where I want

Tags:

excel

vba

For my work I sometimes want to automatically create buttons located at a specific place, with a given width and height.

My code for this is

Sub Add_Button(my_top, my_left, my_Width, my_Height)
Dim myBtn As Object, i As Integer
   Set myBtn = ActiveSheet.Buttons.Add(1, 1, 1, 1)
   With myBtn
      .Top = Cells(my_top, my_left).Top
      .Left = Cells(my_top, my_left).Left
      .Height = Cells(my_top, my_left).Height * my_Height
      .Width = Cells(my_top, my_left).Width * my_Width
      .Caption = text
      End With
End Sub

So the code is pretty straight forward I would say. I call this Sub with the following line

Sub Test_Add_Button()
my_top = 2
my_left = 60
my_Width = 2
my_Height = 3

Add_Button my_top, my_left, my_Width, my_Height
End Sub

And now my problem is that this works fine when the spreadsheet is on my main monitor. However, when it is on my secondary monitor (laptop monitor, which is smaller, but shouldn't matter, I guess) the button is not placed correctly (see the image). Since I sometimes have to add several buttons, it is quite cumbersome to manually place them and reshape them as they are supposed to be.

Additional info, which might or might not be important - I have changed the width of all the cells to 10 pixels.

Another additional note, the further I place the box on the right, the bigger is the discrepancy between the actual placement and the wanted placement.

The image: once button got created on the main monitor, once on the right (smaller, laptop) monitor. added image - once button got created on main monitor, once on right monitor

like image 708
Lukas Avatar asked Nov 06 '22 11:11

Lukas


1 Answers

I've not had any problems adding a button using this code. This has worked over three monitors - laptop and two desk monitors.

Public Sub Add_Button(Target As Range, Caption As String)

    Dim myBtn As Object

    Set myBtn = Target.Parent.Buttons.Add(Target.Left, Target.Top, Target.Width, Target.Height)
    myBtn.Caption = Caption

End Sub

Public Sub Test()

    Add_Button ThisWorkbook.Worksheets("Sheet1").Range("H2:H5"), "My Button"

End Sub
like image 198
Darren Bartrup-Cook Avatar answered Nov 15 '22 07:11

Darren Bartrup-Cook