【问题标题】:Writing logic questions in Excel在 Excel 中编写逻辑问题
【发布时间】:2018-01-17 07:19:21
【问题描述】:

在构建更复杂的规则引擎(在 Prolog 中)之前,我想在 Excel 中编写一系列条件语句(规则?)以进行概念验证

目标是能够将这些语句应用于不同的文本主体,根据触发的规则数量对每个语句进行评分。

我已将文章分开,以便每个单词都在自己的单元格中。例如 A1 字 1、A2、字 2、A3 字 3 等

示例逻辑语句。

如果“football”位于“american”两侧的 5 个单词内,则得分为 +5

如果“曲棍球”位于“场”任一侧的 5 个单词内,则得分为 +10

如果“曲棍球”位于“冰”任一侧的 5 个字以内,则得分为 +20

这很容易做到吗?有人提到嵌套 if 错误查找,但这超出了我的理解。

另外,我已经探索过用其他语言查看此内容,但目前我无法编写代码以及项目的其他部分在 Excel 中工作,所以我有点依赖它。这些部分确实涉及宏,但因此愿意为此探索该选项。

您将如何在 VBA 中实现这一点?

谢谢

【问题讨论】:

  • 你需要看看你是如何为一件事定义一个词的。它实际上必须存在于字典中,还是只是字符(字母和数字)的组合,两边都有空格?如果它的定义空格,您可以先计算每个单词前后有多少空格,看看两边是否有 5 个单词。然后,您可以检查您的单词是否开始大于或小于目标单词两侧的第 5 个空格。在 VBA 中更容易做到,但使用公式并非完全不可能。真的很丑。可能有多个中间单元格。
  • 看看下面的函数,FIND、SEARCH、AND、OR、IF
  • 当你说你已经将每个单词分开时,哪些单词?你正在搜索的句子在哪里? 2-3 行示例数据可能会有所帮助。
  • 纯 Excel 听起来是不是的完美方式。还有其他你熟悉的技术吗?这是可能的,但它需要在 Excel 中使用一些非常 乏味的公式,如果您添加一列,您可能需要费力地重写这些公式。相反,在几乎任何编程语言中,这都容易得多。事实上,我不确定您是否应该直接在 Prolog 中构建您的原型。即使您需要学习它,首先在 Excel 中复制逻辑似乎也是一种浪费,因为没有任何复杂性真正转移。
  • 另一种选择是利用现有技术,无需任何编程即可执行此类查询,例如 SQL Server's full-text searchNEAR 运算符,即使在 SQL Server 的免费版本中也受支持(尽管 @987654322 @)。

标签: excel if-statement logic


【解决方案1】:

我想这可以被清理和重构,但是一些快速而肮脏的 vba 可以作为 UDF 执行此操作:

Function word_proximity_test(sentence As String, word1 As String, word2 As String, distance As Integer) As Boolean
    'Dim a variant for an array
    Dim words As Variant
    'Dim a string for each array element
    Dim word As Variant
    'Dim some integers for holding the positions of word1 and word2 when found
    Dim word1pos As Integer, word2pos As Integer
    'Dim integer to track position in array
    Dim arrPos As Integer

    'Split the sentence into the array
    words = Split(sentence, " ")

    'Iterate the words array
    arrPos = 1
    For Each word In words

        'Test for word1
        If word = word1 Then
            'set the position for word1
            word1pos = arrPos
            'Test if the word2 has been found and if the distance between them is within the distance specified
            If word2pos >= 1 And word1pos - word2pos <= distance Then
                'Return true and exit
                word_proximity_test = True
                Exit Function
            End If
        End If

        'Test for word2
        If word = word2 Then
            word2pos = arrPos
            If word1pos >= 1 And word2pos - word1pos <= distance Then
                word_proximity_test = True
                Exit Function
            End If
        End If


        'increment arrPos
        arrPos = arrPos + 1
    Next word
End Function

将它放到工作簿的新模块中(保存工作簿),然后您可以在单元格公式中使用它,例如:

 =word_proximity_test(A1, "football", "american", 5)

如果 A1 的单词 football 和 American 相距在 5 个单词之内,则返回 true 或 false。

【讨论】:

  • 哇!谢谢,这看起来会很有效。我会试一试并评论结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多