VBA将字符串转换为逻辑序列

时间:2015-03-18 16:34:11

标签: string excel vba excel-vba logic

我正在使用以下类型的信息进行数据库导出:

TestID  | Logic                      | Criterion_1 | Criterion_2 | ... | Criterion N
---------------------------------------------------------------------------------------
101     | 1 AND 2                    | Apple       | California  | ... | Space Quest 6
102     | (1 OR 2) AND (3 OR 5 OR 6) | Banana      | New Jersey  | ... | Scorched Earth

然后,我的程序会将其与某些数据进行比较,并查看条件是否与满足逻辑的某种模式中的数据匹配。在我的理想世界中,我可以使用逻辑字符串并用测试替换数字:

(DataElement_1 = Criterion_1) AND (DataElement_2 = Criterion_2)

对于测试101.当然,简单地替换那些不符合逻辑的部分。在VBA中是否有某种方式来评估它,就好像它是代码内逻辑一样?或许,有一种更好的方式可以做到这一点,我完全忽视了吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

Sub ert()
LastRow = Worksheets("data").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row 'finds the last row with data on the "data" sheet
For i = 1 To LastRow 'for each row
    evalstr = "=" & Cells(i, 2).Value 'creates a function from the statement in column "B" 
    evalstr = Replace(evalstr, "AND", "*") 'replaces the "AND" operator with a logical multiplication 
    evalstr = Replace(evalstr, "OR", "+") 'replaces the "OR" operator with a logical addition
    For j = 1 To 7 'for each condition
         evalstr = Replace(evalstr, CStr(j), Cells(i, 2 + j).Value = ActiveWorkbook.Names("Criterion_" & j).RefersToRange.Value) 'replace the reference with the applicable evaluation
    Next
    Worksheets("data").Cells(i, 10) = evalstr 'inserts the formula to your "J" column
Next
End Sub

test worksheet上正常工作。