如何通过多行而不是硬代码单元循环VBA功能?

时间:2018-10-09 11:05:29

标签: excel vba excel-vba

我有3个功能:

  • 一个可以将以英尺和英寸为单位的高度转换为米。
  • 一个人将石头和磅的重量换算成千克。
  • 一个人的体重指数是用体重除以身高的平方得出的。

问题是,我的函数从精确的单元格读取值并将计算的值放入精确的单元格,这意味着我无法对下面的每一行重复计算。

查看此屏幕截图:

BMI Calculator Data

这是我的代码:

Option Explicit

Const KgRate As Double = 0.45359237     'number of kg in one pound
Const PoundsInStone As Integer = 14     'number of pounds in one stone

Const InchesInFeet As Integer = 12      'number of inches in one foot
Const CmsInInch As Double = 2.54        'number of centimetres in an inch

Public weightInKilograms As Double

Public finalHeight As Double

**' FUNCTION 1**
Public Function heightInMetres()

Dim numberOfFeet As Integer
Dim numberOfInches As Integer
Dim heightInInches As Integer
Dim heightInCms As Integer

numberOfFeet = Range("C4").Value
numberOfInches = Range("C5").Value

heightInInches = (numberOfFeet * InchesInFeet) + (numberOfInches)
heightInCms = heightInInches * CmsInInch
finalHeight = heightInCms / 100

Range("C7") = finalHeight

End Function

**' FUNCTION 2**
Public Function weightInKilos()

Dim stonesEntered As Integer
Dim poundsEntered As Double
Dim stonesToPounds As Double

stonesEntered = Range("C10").Value
poundsEntered = Range("D10").Value

stonesToPounds = stonesEntered * PoundsInStone

weightInKilograms = ((stonesToPounds + poundsEntered) * KgRate)

Range("E10") = weightInKilograms

End Function

**' FUNCTION 3**
Public Function calculateBMI()

Dim BMI As Double

BMI = weightInKilograms / (finalHeight ^ 2)

Range("F10") = BMI

End Function

**' MAIN PROCEDURE**
Public Sub BMICalculator()

heightInMetres
weightInKilos
calculateBMI

End Sub

1)对第1周以下3行(Excel中的第10行)重复权重和BMI计算的最简单方式是什么?

2)是否可以(简单地)连续运行代码,例如我一旦更新身高和体重细胞,就可以重新进行计算吗?

3)如果您建议对代码进行任何(简单)增强,请这样做。 :-)

预先感谢

Pete

1 个答案:

答案 0 :(得分:3)

我在这里更改了其中一个功能,如果可以遵循,则转换其他功能应该没问题:

Public Function heightInMetres(numberOfFeet As Integer, numberOfInches As Integer)

 Dim heightInInches As Integer
 Dim heightInCms As Integer

 heightInInches = (numberOfFeet * InchesInFeet) + (numberOfInches)
 heightInCms = heightInInches * CmsInInch
 finalHeight = heightInCms / 100

 heightInMetres = finalHeight

End Function

因此,现在,只需将以下内容输入到单元格中即可。 C7:

=heightinmetres(C4,C5)

英尺数以C4为单位,英寸为C5(在您的示例中)