简体   繁体   中英

Custom currency format based on another cell value

In cell A1 i might have one of the following currencies "EUR", "USD" or "RON". In cell B1 i have the following custom cell format: "EUR" * 0.00"/mt"

Can anyone help in telling me how can i set the format in cell B1 to adapt taking into account the value from A1. The code must run only at workbook.open

Thank you in advance!

Place the following Event Macro in the worksheet code area:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim A1 As Range, B1 As Range, BaseFormat As String
    Dim temp As String

    Set A1 = Range("A1")
    Set B1 = Range("B1")
    BaseFormat = """EUR"" * 0.00""/mt"""
    If Intersect(A1, Target) Is Nothing Then Exit Sub
    temp = A1.Value
    B1.NumberFormat = Replace(BaseFormat, "EUR", temp)
End Sub

Because it is worksheet code, it is very easy to install and automatic to use:

  1. right-click the tab name near the bottom of the Excel window
  2. select View Code - this brings up a VBE window
  3. paste the stuff in and close the VBE window

If you have any concerns, first try it on a trial worksheet.

If you save the workbook, the macro will be saved with it. If you are using a version of Excel later then 2003, you must save the file as .xlsm rather than .xlsx

To remove the macro:

  1. bring up the VBE windows as above
  2. clear the code out
  3. close the VBE window

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

and

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

To learn more about Event Macros (worksheet code), see:

http://www.mvps.org/dmcritchie/excel/event.htm

Macros must be enabled for this to work!

(to run this only at workbook open, have the Workbook Open macro re-assert the value in A1 and then disable events)

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