【问题标题】:VBA Convert String to Logic SequenceVBA 将字符串转换为逻辑序列
【发布时间】:2015-03-18 16:34:11
【问题描述】:

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

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

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

(DataElement_1 = Criterion_1) AND (DataElement_2 = Criterion_2)

对于测试 101。当然,简单地更换这样的部件是不合逻辑的。 VBA 中是否有某种方法可以评估它,就好像它是代码内逻辑一样?有没有我完全忽略的更好的方法?

谢谢!

【问题讨论】:

  • 如果您认为我的解决方案或其他解决方案有帮助,请随时点赞和/或标记为答案。 回答者和你一样,但是当他们需要答案时,他们通常必须提供赏金。
  • 我很想投票或设置赏金,但我缺乏这样做的声誉。 :(

标签: string vba excel logic


【解决方案1】:
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 上运行良好。

【讨论】:

  • 哦,太聪明了!非常喜欢!
猜你喜欢
  • 2020-01-14
  • 2014-04-04
  • 2018-01-05
  • 1970-01-01
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
  • 2014-07-11
  • 1970-01-01
相关资源
最近更新 更多