Excel VBA函数 - 向单元格中的每个单词添加“+”,但有异常

时间:2016-06-28 10:08:43

标签: excel-vba vba excel

我在这里找到了一个几乎相同的问题。 @KazimierzJawor发布了一个解决方案(子)。我想要做的是将他的解决方案变成一个函数,该函数将使用传入的单个值:

Function AddPlus(word As String) As String
 Dim tmpWords As Variant
 Dim SkipWords As Variant
 SkipWords = Array("в", "от", "под", "над", "за", "перед")
 Dim i As Integer, j As Integer
 Dim Final As String, boExclude As Boolean
 tmpWords = Split(word.Value, " ")
 For i = 0 To UBound(tmpWords)
  For j = 0 To UBound(SkipWords)
   If UCase(SkipWords(j)) = UCase(tmpWords(i)) Then
    boExclude = True
   Exit For
   End If
  Next j
  If boExclude = False Then
   Final = Final & "+" & tmpWords(i) & " "
  Else
   Final = Final & tmpWords(i) & " "
  End If
  boExclude = False
 Next i
word = Left(Final, Len(Final) - 1)
Final = ""
End Function

但是,此函数会在行

中引发错误“无效限定符”
tmpWords = Split(word.Value, " ")

我知道这一定非常容易,但我对VBA很新,并且还没弄清楚如何解决这个问题。也许这里有人可以帮助我?

2 个答案:

答案 0 :(得分:0)

应该是:

Function AddPlus(word As String) As String
Dim tmpWords As Variant
 Dim SkipWords As Variant
 SkipWords = Array("в", "от", "под", "над", "за", "перед")
 Dim i As Integer, j As Integer
 Dim Final As String, boExclude As Boolean
 tmpWords = Split(word, " ")
 Final = ""
 For i = 0 To UBound(tmpWords)
  For j = 0 To UBound(SkipWords)
   If UCase(SkipWords(j)) = UCase(tmpWords(i)) Then
    boExclude = True
   Exit For
   End If
  Next j
  If boExclude = False Then
   Final = Final & "+" & tmpWords(i) & " "
  Else
   Final = Final & tmpWords(i) & " "
  End If
  boExclude = False
 Next i
AddPlus = Left(Final, Len(Final) - 1)    
End Function

答案 1 :(得分:0)

您可能希望处理命名约定。

  • Word误导了多个单词
  • SkipWords是一个数组。我很喜欢这个,但我更喜欢使用ar作为数组的前缀。 arSkipWords
  • 决赛是其他语言的关键词。虽然可以接受,但却具有误导性。结果是包含函数最终结果的变量的标准名称。

在我的版本中,我将 For i Loop 替换为For Each w因为我觉得它更容易阅读。我用Filter函数替换了 For j Loop 因为我认为它是一个很酷的函数。通过将过滤器比较选项设置为vbTextCompare,无需使用UCase。

Function AddPlus(words As String) As String
    Dim w As Variant
    Dim arSkipWords As Variant
    Dim result As String

    arSkipWords = Array("в", "от", "под", "над", "за", "перед")

    For Each w In Split(words, " ")
        If UBound(Filter(arSkipWords, w, True, vbTextCompare)) = -1 Then
            result = result & w & "+"
        End If
    Next
    AddPlus = Left(result, Len(result) - 1)
End Function