如果一个单元格包含一组单词中的一个单词,则检查VBA子句

我正在做一个货物计算器,根据货物是否可以分类为pipe道,盘子或横梁,使用不同的algorithm。 我试图根据货物的描述和尺寸自动检测货物段(如果可以的话,操作员将能够在没有足够数据的情况下手动select一个段)。

我最初的想法是将关键字列表设置为数组; 如果可以纵容一个伪代码的地方,我正在思考这样一些问题:

Pipes = {pipe, tube, conduit, duct} Plates = {plate, sheet, panel} Beams = {beam, rail, girder} IF Description CONTAINS Pipes THEN Calc = "Pipes & Tubes" 

我知道它可以用很多很多的IF子句来完成,但是使用数组或类似的元素可以使得维护列表更容易,因为同义词会突然出现 – 当然这会使代码更加整洁。

任何想法,这样做是一个很好的有效途径?

编辑:澄清,我不是要查看是否在一个数组中find一个完整的string,我试图检查是否在任何一个数组中的单词(或单词的集合,但排列)被发现在描述串。 例如,使用上面的数组, “钢板”应该回到“板”类别中,因为描述中包含“板”。

编辑: @ R3ukfind了一个很好的解决scheme。 这是我最终使用的代码:

在我的声明模块中:public aPipe As String'pipe道同义词数组Public aPlate As String'板同义词数组Public aBeam As String'梁同义词数组

在我的pipe理模块中:aPipe =“pipe / tube / conduit / duct”aPlate =“plate / sheet / panel”aBeam =“beam / rail / girder / truss”

在主导入器模块中,在导入子部分:ImpCalcDetect'导入的计算器段检测(实验)

而这一点本身,从R3uk的答案基本上没有改变,但稍作调整,使其不区分大小写:

 Sub ImpCalcDetect() ' Experimental calculator segment detection If Contains_Keyword(LCase(wsCalc.Cells(iImportCounter, 2).Value), aPipe) Then wsCalc.Cells(iImportCounter, 3).Value = "Pipes" If Contains_Keyword(LCase(wsCalc.Cells(iImportCounter, 2).Value), aPlate) Then wsCalc.Cells(iImportCounter, 3).Value = "Plates" If Contains_Keyword(LCase(wsCalc.Cells(iImportCounter, 2).Value), aBeam) Then wsCalc.Cells(iImportCounter, 3).Value = "Beams" End Sub 

 Function Contains_Keyword(Descr As String, KeyWordS As String) As Boolean Dim A() As String, IsIn As Boolean, i As Integer A = Split(KeyWordS, "/") IsIn = False For i = LBound(A) To UBound(A) If InStr(1, Descr, A(i)) Then IsIn = True Exit For Else End If Next i Contains_Keyword = IsIn End Function 

非常感谢!

你确实可以使用数组,这里是一个string版本,你只需要用斜杠/分隔关键字:

 Sub Test_AndrewPerry() Dim Pipes As String, Plates As String, Beams As String Pipes = "pipe/tube/conduit/duct" Plates = "plate/sheet/panel" Beams = "beam/rail/girder" If Contains_Keyword(Description, Pipes) Then Calc = "Pipes & Tubes" Else 'Nothing to do? End If End Sub 

和“解压缩”string和testing每个关键字,直到它find一个匹配的function:

 Function Contains_Keyword(Descr As String, KeyWordS As String) As Boolean Dim A() As String, IsIn As Boolean, i As Integer A = Split(KeyWordS, "/") IsIn = False For i = LBound(A) To UBound(A) If InStr(1, Descr, A(i)) Then IsIn = True Exit For Else End If Next i Contains_Keyword = IsIn End Function