Paste Name into Formula Excel

Paste Name into Formula Excel

Names:

Name can be used as reference in formulas inspite of cells address. If you have created your name for specific range you can put it into the formula to refer the same (Please refer my article Name in Excel)

To Paste name into formula follow the steps:

  1. In the formula bar, place the insertion point where you want the name to appear.
  2. Choose InsertNamePaste (or press F3). Excel displays the Paste Name dialog box, shown in below screenshot
  • A dialog appears having list of available name which you can paste as shown below:

Finally your formula bar will have name inserted into as show below where I am doing a simple multiplication with “G2” range:

Let’s put some code to achieve the same using automation, In this article I am following VSTO (Visual Studio Tools for Office) with c# and VB style code also a VBA (Visual Basic for Applications)

C# code style:

private void btnInsertFormula_Click(object sender, RibbonControlEventArgs e)
{
	//get active workbook reference
	excel.Workbook oWorkbook = Globals.ThisAddIn.Application.ActiveWorkbook;
	
	//get Range
	excel.Range oRange = Globals.ThisAddIn.Application.Selection;
	
	//get Name
	excel.Name oName = oWorkbook.Names.Item("VBAOVERALL");
	
	//Put name into formula
	oRange.Formula= "=" + oName.Name + "* 25";
	
}

VB.Net code example:

Private Sub Button1_Click(sender As Object, e As RibbonControlEventArgs) Handles Button1.Click
	'Bind worksheet object reference
	Dim oWorkSheet as excel.Worksheet
	oWorkSheet = Globals.ThisAddIn.Application.ActiveSheet

	'Bind Range object from selection
	Dim oRange As excel.Range
	oRange=Globals.ThisAddIn.Application.Selection

	'Get name
	Dim oName as excel.Name
	oName=oWorkSheet.Names.Item("VBAOVERALL")

	'Put formula
	oRange.Formula= "=" + oName.Name + "* 25"
End Sub

VBA code example:

Public Sub InsertName()
    'Sheet reference
    Dim oWorkbook As Workbook
    Set oWorkbook = ActiveWorkbook
    
    'selection reference
    Dim oRange As Range
    Set oRange = Selection
    
    'Get name
    Dim oName As Name
    Set oName = oWorkbook.Names("VBAOVERALL")
    
    'Insert formula
    oRange.Formula = "=" & oName.Name & " * 25"
End Sub

Next >> Trace Precedents in Excel

Leave a Reply

Your email address will not be published.