2016-06-28 70 views
0

我在這裏找到了一個題目幾乎相同的問題。 @KazimierzJawor發佈了一個解決方案(子)。我想要做的就是把他解到一個函數,將與通過單個值工作:Excel VBA功能 - 爲單元格中的每個單詞添加「+」,但有例外

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很陌生,並沒有想出如何解決這個問題。也許這裏有人可以幫助我?

+1

'word'是一個字符串變量,它沒有像'.value'這樣的屬性,所以刪除它。 –

+0

@AlexK。是的,我自己找到了。然而,該函數返回空值,無論什麼「字」傳入(西里爾)。我不明白爲什麼,因爲它應該工作(在這裏有另一個主題很好的工作) –

回答

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 
0

您可能希望在您的命名約定的工作。

  • 字是誤導它的多個單詞
  • SkipWords是一個數組。我對這個很好,但我更喜歡用ar作爲數組的前綴。 arSkipWords
  • Final是其他語言的關鍵詞。雖然可以接受,但這是誤導。結果是保存函數最終結果的變量的標準名稱。

在我的版本中,我將For i Loop替換爲For Each w,因爲我認爲它更易於閱讀。我用Filters函數替換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