我想在Excel中编写一系列条件语句(规则?),以便在构建更复杂的规则引擎之前进行概念验证(在Prolog中)
目标是能够将这些语句应用于不同的文本主体,根据触发的规则数量对每个语句进行评分。
我已将文章分开,以便每个单词都在自己的单元格中。例如A1字1,A2,字2,A3字3等
逻辑语句示例。
IF" football"位于"美国"两侧的5个字内。那么得分为+5
IF"曲棍球"位于" field"的任意一侧的5个字内。那么得分为+10
IF"曲棍球"居住在" ice"的任何一方的5个字内。然后得分+20
这可以轻松完成吗?有人提到嵌套if error vlookups但这超出了我的理解。
或者,我已经探索过用其他语言查看这个内容但是我不能编写代码加上目前项目的其他部分在Excel中工作,所以我很喜欢它。这些部分确实涉及到宏,因此可以开始探索这个选项。
你如何在VBA中实现这一目标?
由于
答案 0 :(得分:1)
我认为这可以被清理和重构,但是作为UDF的一些快速和脏的vba将是:
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在每个单词的5个单词中包含单词football和american,则返回true或false。