Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

How to position a VBA UserForm near a cell

0

Hi John, 

Many thanks once again for providing guidance (https://www.teachexcel.com/talk/7531/copy-and-paste-a-named-range) for using VBA to copy a named range and paste it to a specific location. I've attached the excel document you were kind enough to prepare in which the VBA code replicates the Lotus123 feature. (I'm not sure why the width of the userform is cut short and I couldn't find how to fix it.)

I would like to ask your help for a final detail to improve it. 

Is it possible to position the userform near the selected cell? 

PS. Although you gave the answer to the following question on the discussion of the previous answer, I wanted to include my follow up question here so others could benefit from your input: After a name range is pasted to the selected cell, would it be possible to add the option to press "ESC" to close the userform when I'm done pasting? Currently one needs to use the pointer to click the close button on the corner.  

Regards,

Ezybao

Answer
Discuss

Discussion

Ezybao. Please see my revised Answer and also delete the second file in your Question (to svoid confusing othets). 
John_Ru (rep: 6142) Jan 25, '24 at 1:41 pm
Add to Discussion

Answers

0
Selected Answer

Hi again Ezybao

In the FIRST attached revised file:

  1. pressing Ctrl+J in the "Quotation" worksheet positions the UserForm just to the right and down from the selected cell
  2. if a valid code is typed (i.e. one found in the Database sheet column A), the form goes green to say that code was found and typing Enter key will paste it in the selected cell (as in my previous Answer Copy and paste a named range)
  3. if the user presses Enter on an invalid code, a warning message box appears
  4. if the user presses Esc at any time, the UserForm is closed.

It uses using a new UserForm control feature- the KeyDown event and checks each key depression. The Enter and Esc keys are identified by the specific keyboard constants shown in bold below (with some explanatory comments):

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    ' close UF if ESC pressed
    If KeyCode = vbKeyEscape Then Unload Me
    ' do nothing if no entry in ComboBox1
    If TextBox1.Text = "" Then Exit Sub
    ' otherwise entry exists so loop through the Names in the array to check entry is a code
    For n = 1 To UBound(Cds)
        If TextBox1.Text = Cds(n) Then
            ' if text is a valid code, paste and advise user
            Range(Cds(n)).Copy Selection.Resize(1, 1)
            ' ... prevent Textbox change re-triggering by actions below
            Me.DisableUFevents = True
            ' set the form to grey and label + text to nothing
            UserForm1.BackColor = -2147483633
            Label1.BackColor = -2147483633
            Label1.Caption = Cds(n) & " was pasted to " & Selection.Address(0, 0)
            TextBox1.Text = ""
            Me.DisableUFevents = False
            ' move down a cell (for the next code entry)
            Selection.Offset(1, 0).Resize(1, 1).Select
            Exit For
        End If
    Next n
    ' if the Enter button was pressed and code was NOT found..
    If KeyCode = vbKeyReturn And n = UBound(Cds) + 1 Then
        ' ..say and quit
        MsgBox "Code not found, please try again"
        Exit Sub
    End If
End Sub

Important: the positioning relies on the UserForm property Startup Position being set to 0 - Manual before the UserForm is launched- it MUST be set in the UserForm design (like I have done)- it cannot be set during run time, e.g. in the UserForm_Initialize code.

Revision 25 January 2024:

In Windows (at least), the form is then positioned by the bold lines in the procedure below:

Private Sub UserForm_Initialize()

    ' size the array to hold all names
    ReDim Cds(ActiveWorkbook.Names.Count)

    p = 1
    ' loop through the Names
    For n = 1 To ActiveWorkbook.Names.Count
        ' look at the nth Name
        CdNm = ActiveWorkbook.Names(n).Name
          ' if the range is on the Database sheet...
        CdRng = ActiveWorkbook.Names(n).RefersTo
        If InStr(1, CdRng, "Database", vbTextCompare) > 0 Then
          ' add the Name to the array
          Cds(p) = CdNm
          p = p + 1
        End If
    Next n

    ' resize the array to remove any unused locations
    ReDim Preserve Cds(p - 1)
    ' put cursor in textbox, ready for typing
    TextBox1.SetFocus

    ' for UF...
    With Me
        ' allow code changes to occur
        .DisableUFevents = False
        ' position UF to right of cell
        .Left = Application.Left + ActiveCell.Left + ActiveCell.Width + 20
        .Top = Application.Top + (Application.Height - Application.UsableHeight) + ActiveCell.Top
    End With

End Sub

Revision 2 25 January 2024

Differences on the Mac mean the above approach doesn't work on that platform since the .Top isn't treated the same as on a PC (but a hint was found by EzyBao on Ron de Bruin's website). Accordingly...

The SECOND attached file replaces the code behind sheet 1 "Quotation" with this:

Sub PasteCode()

    '

    ' PasteCode Macro

    '

    ' Keyboard Shortcut: Ctrl+j

    '

    ' place the form

    With UserForm1

        ' position UF to right of cell

        .Left = Application.Left + ActiveCell.Left + ActiveCell.Width + 20

        ' position the top, depending on platform (Mac or PC)

        #If Mac Then

            .Top = Application.UsableHeight - Application.Top + (Application.Height - Application.UsableHeight) + ActiveCell.Top



            #Else ' for PC...

            .Top = Application.Top + (Application.Height - Application.UsableHeight) + ActiveCell.Top

        #End If

    ' display

    .Show

    End With



End Sub

(That code in bold is removed from the UserForm_Initialize procedure.)

Hope this is what you need. If so, please be sure to mark this Answer as Selected.

Discuss

Discussion

Hi John, I apologize for not posting a new question earlier. I had missed your answer. 

In the new file you have provided, pressing ESC works perfectly however the positioning of the UF is not correct on my laptop. I've edited my original question to add a 2nd Excel file which includes screenshots of where the UF is located for me. 

I'm a MAC user, but most of my colleagues use Windows. I believe the solution is explained here: https://macexcel.com/examples/userforms/userformposition/#:~:text=StartUp%20Position%20UserForm,but%20not%20in%20Mac%20Excel.

Being unfamiliar with VBA, I've failed to apply the solution myself. Would it be possible to add a similar IF code with two blocks for both windows and mac?
ezybao (rep: 16) Jan 25, '24 at 8:40 am
Ezybao

I'm not a Mac user, don't have access to one and I don't have time to investigate the differences (for at least 3 days) sorry.

The link to (the brilliant) Ron de Bruin's page isn't the full answer  unfortunately and your screenshots seem to show that the Mac handles UserForm design differently too.

Can you please ask one of your colleagues to try my file on a PC (or take a copy to them and try yourself)? If it works well on a PC it might make sense to investiage a little more next week. Otherwise I'll be tempted to forget it.

Please confirm what you find.
John_Ru (rep: 6142) Jan 25, '24 at 9:41 am
p.s. please remove that second file now- I have seen it but it would simply confuse other Forum users.
John_Ru (rep: 6142) Jan 25, '24 at 9:43 am
Ezybao - I just revised my Answer since I'd missed off the code to position the Windows) UserForm.

Please respond to my points above however.
John_Ru (rep: 6142) Jan 25, '24 at 11:29 am
Ezybao- please see Revision 25 January 2024 to my Answer (plus the second file). It works on my PC- does it now work on your Mac?
John_Ru (rep: 6142) Jan 25, '24 at 12:40 pm
Hi John, many thanks for your response. I've edited my original question to delete the 2nd spreadsheet. 

For Windows users your code works perfectly and as you said the userform design is different as well. Unfortunately, the positioning for MAC did not work. When the applicaiton is in full height, the userform cannot be seen at all. As I start to make the window shorter, the UF becomes visible below the application. As I continue to make the application shorter, the UF starts to be seen on the spreadsheet. 

I don't want to take any more of your time with this, thank you once again for your help!
ezybao (rep: 16) Jan 25, '24 at 2:36 pm
Thanks for selecting my Answer Ezybao - that's kind of you, given my Mac addition didn't work. Sorry I couldn't help more but if you want to buy me a Mac... ; -)

I may try again in the next few days, if time permits.
John_Ru (rep: 6142) Jan 25, '24 at 2:53 pm
Many thanks :)
ezybao (rep: 16) Jan 26, '24 at 2:41 am
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login