【问题标题】:Checking in a VBA sub if a cell contains a word from a set of words如果单元格包含一组单词中的一个单词,则检查 VBA 子
【发布时间】:2016-03-21 10:23:16
【问题描述】:

我正在开发一个货物计算器,该计算器根据货物是否可以分类为管道、板或梁使用不同的算法。我试图让它根据物品的描述和尺寸自动检测货物段(如果可以的话;如果没有足够的数据,操作员将能够手动选择一个段)。

我最初的想法是将关键字列表设置为数组;如果可以放纵一点伪代码,我正在考虑以下几点:

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

我知道这可以通过大量的 IF 子句来完成,但是使用数组或类似的东西会更容易在出现同义词时维护列表 - 当然也会使代码更整洁。

有什么好的有效方法吗?

编辑: 澄清一下,我不是要查看是否在数组中找到了整个字符串,而是要检查数组中是否有任何单词(或单词,无论如何排列)在描述性字符串中找到。例如,使用上面的数组,“Steel sheet” 应该返回到“Plates”类别,因为描述包含“sheet”。

编辑: @R3uk 找到了一个很好的解决方案。这是我最终使用的代码:

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

在我的管理模块中: aPipe = "管道/管子/导管/导管" aPlate =“板/片/面板” aBeam = "梁/轨道/大梁/桁架"

在主导入器模块中,在导入子模块中: 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

非常感谢!

【问题讨论】:

  • 谢谢,但这并不是我想要的——我正在尝试检查是否在描述中找到了每个集合中的任何单词。例如,如果描述是“碳钢导管”,它应该与集合“管道”中的“导管”匹配

标签: vba excel


【解决方案1】:

您确实可以使用数组,这是一个字符串版本,您只需要用斜线 / 分隔关键字:

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

以及“解压缩”字符串并测试每个关键字直到找到匹配项的功能:

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

【讨论】:

  • 看来它可以工作......谢谢,我会试一试。 :-)
  • 辛苦了,谢谢!我将粘贴上面最终使用的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多