我完全迷失了,需要一些专家建议。
在excel我有一个完整的关键字列,我希望能够使用一个添加" +"的宏。在每个单词之前,除了一组不需要它的单词之外。
所以基本上在VBA代码中需要有一个我可以说的地方"跳过',for,with,"等。
编辑:我只找到了允许附加到每个单元格开头的代码。所以这很接近,但并不完全是我正在寻找的东西。我无法找到更接近我需要的东西。
Sub Add_Plus()
Dim r As Range
With Selection
For Each r In Selection
r.Value = "+" & r.Value
Next
End With
End Sub
DOUBLE EDIT -
你们真棒!我们非常接近,我只需要宏将+符号添加到每个单元格中的每个单词,但指定为异常的单词除外。非常感谢!
所以我们正在寻找的输出是:
宏观之前的细胞1:快乐的狗欢呼雀跃 宏观之后的细胞: + happy + dog +跳跃+欢乐
答案 0 :(得分:1)
你走了。只需使用一些逻辑来确定何时跳过单词:
Sub Add_Plus()
Dim r As Range
Dim words As Variant
Dim word As Variant
Dim w As Long
Dim exclude As Variant
'Allow user-input to capture a list/array of words to exclude:
exclude = Split(Replace(Application.InputBox("Enter a comma-separated list of words to exclude"), " ", vbNullString), ",")
For Each r In Selection.Cells
'Create an array of "words" from the cell:
words = Split((r.Value), " ")
w = LBound(words)
' iterate over each "word"
For Each word In words
'Make sure the word is not in the excluded list
If Not IsError(Application.Match(word, exclude, False)) Then
' DO NOTHING
Else
' Add the "+" to these words:
words(w) = "+" & word
End If
w = w + 1
Next
r.Value = Join(words, " ")
Next
End Sub
答案 1 :(得分:1)
这可以通过公式轻松完成。
假设"跳过单词"在Sheet2的A列中,然后:
=IF(COUNTIF(Sheet2!A:A,A1)=0,"+","")&A1
会这样做。
答案 2 :(得分:1)
这就是我理解你的问题的方法 - 除了被排除的单词之外,单元格中的每个单词都应该有“+”。
尝试以下代码。请参阅下面的一些评论
Sub Add_Plus()
Dim r As Range
Dim SkipWords As Variant
'put all excluded word here, separate, within quotation marks
SkipWords = Array("place", "all", "words", "to", "skip", "here")
Dim tmpWords As Variant
Dim i As Integer, j As Integer
Dim Final As String, boExclude As Boolean
For Each r In Selection
tmpWords = Split(r.Value, " ")
For i = 0 To UBound(tmpWords)
For j = 0 To UBound(SkipWords)
If UCase(SkipWords(j)) = UCase(tmpWords(i)) Then
'do nothing, skip
boExclude = True
Exit For
End If
Next j
If boExclude = False Then
Final = Final & "+" & tmpWords(i) & " "
Else
'this will keep excluded words without "+"
'remove it if you want to remove the excluded words
Final = Final & tmpWords(i) & " "
End If
boExclude = False
Next i
r = Left(Final, Len(Final) - 1)
Final = ""
Next
End Sub
运行代码后,以下单元格:
do re mi
fa sol la
do place all
to words skip
here do re
place all
将被替换为:
+do +re +mi
+fa +sol +la
+do place all
to words skip
here +do +re
place all
答案 3 :(得分:0)
选择您的单元格并运行:
Sub dural()
For Each r In Selection
If r.Value <> "happy" And r.Value <> "sad" Then
r.Value = "+" & r.Value
End If
Next
End Sub
更改排除项以满足您的需求。