Unit conversion with VBA in Microsoft Excel

The worksheet function Convert () offers a large number of conversion options for physical units. They have only existed since Excel 2007. You can also use units with a prefix, such as: B. the "k" for the factor 1,000 as for "km". The following four numerical values (information for distance, energy, temperature and pressure) are converted into another unit. At the same time, they are formatted for a clearer presentation, together with the results of the conversion:

Sub Umrechnungen()
ThisWorkbook.Worksheets("Tabelle2").Activate
' Entfernung
Range("A2").Value = Application.WorksheetFunction. _
Convert(Range("A1").Value, "km", "mi")
Range("A1").NumberFormatLocal = "0,000 ""Km"""
Range("A2").NumberFormatLocal = "0,000 ""Miles"""
' Energie
Range("A5").Value = Application.WorksheetFunction. _
Convert(Range("A4").Value, "J", "cal")
Range("A4").NumberFormatLocal = "0,00 ""J"""
Range("A5").NumberFormatLocal = "0,000 ""cal"""
' Temperatur
Range("A8").Value = Application.WorksheetFunction. _
Convert(Range("A7").Value, "C", "F")
Range("A7").NumberFormatLocal = "0,0 ""Grad C"""
Range("A8").NumberFormatLocal = "0,0 ""Grad F"""
' Druck
Range("A11").Value = Application.WorksheetFunction. _
Convert(Range("A10").Value, "hPa", "mmHg")
Range("A10").NumberFormatLocal = "0,000 ""hPa"""
Range("A11").NumberFormatLocal = "0,000 ""mm HG"""
End Sub

Meters to Miles: In the first case, a distance from meters is converted into British miles. For this, the information km and mi in parameters 2 and 3 are necessary. The prefix k ensures that the value is assumed in kilometers.

Joules to Calories: In the second case, an energy specification is converted from joules to calories. For this, the information J and cal in parameters 2 and 3 are necessary.

Celsius to Fahrenheit: In the third case, a temperature specification from degrees Celsius (C) is converted into degrees Fahrenheit (F).

Air pressure: The last conversion determines an (air) pressure in mm of mercury column (mmHg) from hectopascals (hPa). The h is the prefix for hecto, so one hundred.

Text in the format: All cells have been formatted appropriately. As a reminder: Text within a format must be enclosed in double double quotation marks.

Was the explanation to "Unit conversion with VBA in Microsoft Excel"Helpful? Rate now:

Weitere Erklärungen zu Skriptsprachen