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

Copy and paste a named range

0

Hi Guys, I'm incredibly happy to receive an answer to my first question so quickly; I'm posting a 2nd one. 

Lotus123 has this feature where, with a macro, you can copy and paste a named range. For example, imagine a range with 1 row and 6 columns (from B1 to G1) is named RAMCAP. The values of each column are:

B1- RAMCAP.h24

C1-

D1- =45*1/K/US*BAZ

E1- =45*1/K/US*BAZ/2

F1- RAMADA KAPADOKYA

G1-  

If I do B5=ramcap, these values are shown in B5 to G5. However, I cannot see the formulas in D5 and E5, edit any of the information, or delete or change anything after calling it. What I want to be able to do is for the RAMCAP range to be copied and pasted to B5 so that I can both see the inputs in each individual cell and also change anything if I want to without needing to go and change the values in the database section. I want to do this without going to the database, finding the named range, copying it and coming back to paste it manually. Is it possible to write a macro that first prompts the user to write the "name" and then copies and pastes that range? 

I'm attaching an example document. Many thanks in advance!

Answer
Discuss

Discussion

Hello again ezybao,

I have briefly looked at this and have a couple of questions (since I am not familiar with Lotus 123)

The value in B1: RAMCAP.h24  --  is this a named range or does the ".h24" somehow act on "RAMCAP"
The formulas in D1 & E1: I don't see the need to begin with "45*1" instead of just "45" - because, after all, 45 times 1 is still just 45.

Chances are that John will provide an answer sooner than I can but I will still give it some thought when I have time.
WillieD24 (rep: 557) Jan 6, '24 at 5:06 pm
Hi Willie, you are right of course. to be honest, it doesn't matter what the formulas are, I just wrote these as an example. Most probably that multiplier number was added for some reason in the past then became a "1" and became obsolete. 

In this example, "ramcap" is the shortened version for "Ramada Hotel in Cappadocia". H.24 means the price in the database has been updated with 2024 values, so it is just a text (name). We update that name as we update the cost to the current year but the name of the named range is always "ramcap" so everyone knows that to call when they're calculating a quotation. 
ezybao (rep: 16) Jan 7, '24 at 4:32 am
Add to Discussion

Answers

0
Selected Answer

Hi again Ezybao

You didn't attach a file to your original Question (or attempted to attach Lotus 123 file- but this Forum only allows Excel files to be uploaded).

Also your Forum Profile doesn't say which version of Excel you are using.

It's easy enough to copied a named range, paste it and rename in a few clicks (without VBA)...

In the FIRST attached file I've tried to recreate what you describe, with named range RAMCAP in yellow cells B1:G1 and  US, K and BAZ in coloured cells A2, A4 and A6 respectively. Note that C2 is blue since I changed the formula to multiply it by C1 (which I set to 45), so (changes in bold):

=C1*45*1/K/US*BAZ

To copy the range RAMCAP:

  1. click in any single cell then click the down arrow where the cell name (e.g. B5)  appears (to the left the formula bar normally)
  2. Click on RAMCAP in the list of named ranges (the selection will change to B1:G1)
  3. press Ctrl+C to copy the range (dotted lines will appear around it)
  4. click in the desired cell (say B5) and press Ctrl+V- the cells will be copied including any formula
  5. without changing the selection, go ribbon Formulas then click Name Manager (under the Defined Names section)
  6. in the Name Manager requestor, click New... then in the next requestor, name the new range under Name: and click OK

The formulae are copied relatively (so C1 will be C5- so chnage that and D5 will alter to suit.

It's probably easier to learn this simple method unless you have to do this many times- when it might warrant your (/my spare) time to write the VBA code to cover it.

Revision 08 January 2023

From the Discussion below, I now understand you have hundreds or thousands of Named ranges to paste into quotations.

In the SECOND attached file, you'll see a spreadsheet with three sheets: Quotation, Database and Variables (the latter just storing formula variables like K, US and BAZ). I made up some (coloured) Named ranges in the sheet Database, listing their names in column A (take a look). 

If yoiu open the file (with macros enabled), go to the Quotations sheet, selct a cell in column B (say) and press Ctrl+j - this will caused the code behind that sheet to run:

Sub PasteCode()
    '
    ' PasteCode Macro
    '
    ' Keyboard Shortcut: Ctrl+j
    '
    ' display the form
    UserForm1.Show
End Sub

since it is "assigned" to the key combination Ctrl plus j (you can change that).

That brings up UserForm1 which runs this code and gets puts the all the named ranges from the worksheet Database into an array called Cds - for Codes. I've added comments so you see what is happening:

Private Sub UserForm_Activate()

    ' 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
    ' allow events to occur
    Me.DisableUFevents = False
End Sub

That uses some varaibles which are declared at the UserForm level (at the top) so they keep their contents by these lines:

Public DisableUFevents As Boolean, Cds As Variant
Public CdNm As String, CdRng As String, n As Long, p As Long
Option Base 1
Option Explicit

As you type into the text box, it looks for an exact match between the contents and what's in the array Cds:

Private Sub TextBox1_Change()
     ' do nothing if change arises from code
    If DisableUFevents = True Then Exit Sub
    ' set the form to grey and label to nothing
    UserForm1.BackColor = -2147483633
    Label1.Caption = ""
    Label1.BackColor = -2147483633

    ' loop through the Names in the array
    For n = 1 To UBound(Cds)
        If TextBox1.Text = Cds(n) Then
                ' if text is a valid code, turn form green and advise user
                UserForm1.BackColor = 8454016
                Label1.Caption = "Found! Press Enter to paste"
                Label1.BackColor = 8454016
                Exit For
            End If
    Next n
End Sub

If you type a code which matches a Named range in Database, you'll see the form turns green (to indicate a match) and suggests you press Enter. If you do, that's detected by this code:

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    ' do nothing unless the Enter button was pressed
    If KeyCode <> vbKeyReturn Then Exit Sub
    ' do nothing if no entry in ComboBox1
    If TextBox1.Text = "" Then Exit Sub
    ' if entry exists...

    ' 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 prevent Textbox change re-triggering by actions below
                Me.DisableUFevents = True
                ' set the form to grey and text + label to nothing
                UserForm1.BackColor = -2147483633
                TextBox1.Text = ""
                Label1.BackColor = -2147483633
                Label1.Caption = Cds(n) & " was pasted to " & Selection.Address(0, 0)
                Me.DisableUFevents = False
                ' move down a cell (for the next code entry)
                Selection.Offset(1, 0).Select
                Exit For
            End If
    Next n

End Sub

which again checks that the code exists and then paste the range into your cell (or starting from the top leftmost cell if you had several selected) and tells you.

It moves the cursor to the next cell down and you can enter another code or press the x (top right of the form to stop.

It might seem like a lot of fairly sophisticated code just to replicate what Lotus123 did but I hope this allows you to work efficiently. You could have thousands of Named ranges in that Database sheet and it will still work quickly (since I used an array for the comparison).

Hope this solves your problem. If so, please remember to mark this Answer as Selected (or do that to another Answer if you get one and prefer that)

Discuss

Discussion

@John_Ru Hi, many thanks for your response. I'm not sure how this question got posted to be honest. When I tried I got the error saying I had to wait for 24 hours. I just came back to the website to post my question and saw it was posted without the excel file. Now I cannot add the file in discussion but thank you for creating a similar one.

So yes, going to the original row and copying it works of course but the file I want to implement this has a database of thousands of suppliers (rows). One can always use goto or a similar search method to what you described to go and copy from the original location come back up to the quotation calculation table and paste it but this is much less efficient than the 20-year-old lotus123 file. On Lotus we activate a macro with a given shortcut (CTRL+C) in the cell we want the named range to be copied to, a window pops up, we write the name "ramcap", press enter, and that name is copied and paste to the location we selected while starting this process. It doesn't require any scrolling or moving around the file. I wondered if it was possible to do something similar in excel but I'm not experienced with VBA so couldn't try anything on my own about this. 
ezybao (rep: 16) Jan 6, '24 at 2:12 pm
Forgot to add I am using the newest version of Excel through microsoft365 on MAC. 
ezybao (rep: 16) Jan 6, '24 at 2:13 pm
Ezybao

You can't add a file to a Discussion but go to your original question, edit and use the Add Files....button. Also, please edit the Question text to point out some range names you might want to copy (or the database sheets). Also do you recall the names (like RAMCAP) from mempory or whould a scrollable list help?

I'll try to take a look at it tomorrow but won't have much spare time.so perhaps won't have time to write working code.

You should add your Excel version to your Profile on the Forum (since it can inform the type of Answer you get). I don't use a Mac (so my keybaord shortcuts like Ctrl+C are for Windows) and I'm aware that the 365 version on Mac is almost itentical but there may be aome thinks that don't work between platforms.
John_Ru (rep: 6142) Jan 6, '24 at 2:42 pm
Hi John, thanks, I'm learning to use the forum. I have now added the excel file to the question. Yeh, 365 version of excel in mac is almost identical, but my colleagues all use windows so it doesn't really matter. Also ctrl c or whatever shortcut that works for you is also fine. If you can show me a way to use vba to prompt the user to enter the "name" for the named range and then copy and paste it to the location, I can then modify it according to our situation. 

We mostly memorized these names so don't really need a scrollable list. When we cannot remember, we scroll down to the database, find what we are looking for and look at it's "name". There are hundreds of hotels, restaurants, entrance fees and so on in the database. While hotel named ranges are with 6 columns, coach prices are with 5, entrance fees only with 2 (name & the cost) and etc. So the ranges are not always identical. If I can understand how to do one, I believe I can figure out the rest, hopefully :)
ezybao (rep: 16) Jan 7, '24 at 4:41 am
Ezybao. Thanks for attaching a file.

It doesn't really emulate the situation you describe so I will create a demo file. I have no time today but should post a demo by the end of tomorrow.

Do you save your formula variables (like K, US and BAZ) in a separate sheet to the quotation calculation table and database?
John_Ru (rep: 6142) Jan 7, '24 at 9:30 am
Hi John, no they're all in the same sheet currently, the whole database is below the quotation table so rows and rows of scrolling :) 
ezybao (rep: 16) Jan 7, '24 at 1:10 pm
Ezybao

Please see Revision 08 January 2023 to my Answer and the second file. After testing it, please don't foget to mark the Answer as Selected if it works for you.
John_Ru (rep: 6142) Jan 8, '24 at 12:51 pm
Dear John, this is precisely what I needed. I appreciate it so much! I'm only wondering if it would be possible to exit the user form automatically when a successful paste-to-cell has occurred. Please let me know if you're ever in Istanbul; I owe you drinks. 
ezybao (rep: 16) Jan 9, '24 at 8:28 am
Glad that worked for you. Thanks for selecting my Answer Ezybao.

If you really want to do Ctrl+j each time, then in the UF procedure Private Sub TextBox1_KeyDown, add a new line before End Sub and add:
Unload Me

(I'm on my phone so going from memory)
John_Ru (rep: 6142) Jan 9, '24 at 8:53 am
P.s. thanks for the offer of drinks, that's a nice gesture but I doubt I'll get to Istanbul (although my daughter and family had a great holiday in Turkey). Anyway I couldn't contact you if I got there! 
John_Ru (rep: 6142) Jan 9, '24 at 9:03 am
Glad to hear that your family have good memories of Turkey. This forum should have a private messaging section to share contact details. 

"Unload Me" worked like a charm. Thank you!

One last question for when you have a bit more free time, could you let me know how I can change the location of the userform? Right now it pops out on the right end of the screen and the text you have written is also cut short as the box width is a bit short. 
ezybao (rep: 16) Jan 9, '24 at 10:08 am
Easybao, In a way, the lack of private messaging on the Forum helps to protect the contributors (who are volunteeers) from being chased privately by users. We give our time for free but some users might take advantage of direct access to us.

Glad the Unload addition worked.

On placing the UserForm, it currently uses the default (so should appear in centre of your PC screen with a single monitor- do you have your desktop extended over dual screens?).

Please ask a new question for this (and attach a file)- note that we generally don't like it when a user asks one question, gets an answer then  asks another extra question then a further one etc., especially if they don't Select a valid Answer to their original question (you didn't make this mistake thankfully), I might answer the new question but so too might Willie or Don.
John_Ru (rep: 6142) Jan 9, '24 at 1:02 pm
Ezybao- good news! I have an Answer (and new file) for you but would still like you to raise a new question (since it requires some explantaion and that should be helpful to others). 

I suggest the question has the title "How to position a VBA UserForm near a cell". Please refer to the earlier Answer and attach your file (My new one includes the Unload Me line)
John_Ru (rep: 6142) Jan 10, '24 at 11:50 am
Add to Discussion


Answer the Question

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