最近由於開發需要,需要編寫將數據庫中的字符串轉化為公式並計算出結果的程序,在網上找了一些資料,很少呀,無奈只有自己動手開刀了,由於是分段函數,所以數據庫中的字符串要含有變量的取值范圍,要把這些取值范圍取出來,對應於相應的函數。
思路是這樣的,在數據庫存放帶格式的公式串,例如“0,4;0.75*x+12|5,10;0.6*x+10|11,~;0.4*x+12”,其中“|”作為公式段的分隔符號,前面兩個數字即為變量的取值范圍,用split函數將字符串分隔好,然後取出即可。
Function ConvertToFormula(ByVal strFormula As String, ByVal Value As Integer) As Decimal
''strFormula = "0,4;0.75*x+12|5,10;0.6*x+10|11,~;0.4*x+12"
Dim mscFormula As New MSScriptControl.ScriptControl ''引用MS Script Control
Dim strArray(), strArray1() As String
Dim strTemp1, s, s1(), s2 As String
Dim decResult As Decimal
Dim i, demension As Integer
mscFormula.Language = "vbscript"
''strFormula = "0,4;0.75*x+12|5,10;0.6*x+10|11,~;0.4*x+12"
If strFormula <> "" Then
strArray = strFormula.Split("|") ''取得"0,4;0.75*x+12"
demension = strArray.GetUpperBound(0)
Dim strFm(demension), x1(demension), x2(demension) As String
For i = 0 To strArray.GetUpperBound(0) - 1
strTemp1 = strArray(i).ToString
strArray1 = strTemp1.Split(";") ''取得"0,4"
s1 = strArray1(0).Split(",") ''Get 0 and 4
s2 = strArray1(1).ToString ''Get "0.75*x+12"