简体   繁体   中英

Setting the value of an excel cell referenced by another cell with VBA

I currently have a spreadsheet called "DataMap" which has a key/value layout. The key is a reference to another spreadsheet and cell, and the value is input by the user.

For example, the key column might have the following individual references:

  • =Sheet1!B25
  • ='Sheet 2'!B25
  • =TableName[TableRowName]

There's also a button called "Transfer Data" on this page.

When "Transfer Data" is pressed, a macro runs which copies the values into the cell referenced by the key column.

The point of this page is to have a single location where data can be injected from a 3rd party system, with no knowledge of the rest of the excel workbook - barring the fact that there's a "DataMap" sheet.

Currently, I loop over each of the key/value pair rows in "DataMap" and can inject the value into "=Sheet1!B25" using the following code:

reference = Replace(Sheets("MAPPINGS").Range("A" & row).Formula, "=", "")
refSplit = Split(reference, "!")

Sheets(refSplit(0)).Range(refSplit(1)) = Sheets("MAPPINGS").Range("B" & row).Value

If I use a string replace, I can handle the "='Sheet 2'!B25" case as well.

I am, however, having significant trouble with the named tables.

Is it possible? Or, alternatively, does anyone have a suggestion of a better way to specifically handle the copying of a value into a cell referenced by the 'key' column (regardless of the format of the reference)?

Thanks

Dim sht As Worksheet
Dim ref As Range

Set sht = Sheets("MAPPINGS")

Set ref = Application.Evaluate(Replace(sht.Range("A" & Row).Formula, "=", ""))
ref.Value = sht.Range("B" & Row).Value

See below.

Dim sht As Worksheet
Dim address As Range

Set sht = Sheet2

Set address = Range(Replace(sht.Range("A" & 5).Value, "=", vbNullString))
address.Value = sht.Range("B" & 5).Value

Couple of suggestions:

  1. Change Sheets("MAPPINGS") to the internal name of the sheet (found in the VBA window) so if the sheet name is changed in Excel it will not impact your macro.
  2. Do not add the "=" in the cell reference so you dont need the replace syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM