在Excel中的单元格中添加一个字符w /选项跳过某些单词

我完全失去了,需要一些专家的意见。

在Excel中,我有一列充满了关键字,我希望能够使用一个macros,每个单词前加一个“+”,除了一组不需要它的单词。

所以基本上在VBA代码中需要有一个地方可以说“跳过”,“为了”,等等。

编辑:我只发现允许附加到每个单元格的开始的代码。 所以这很接近,但不是我正在寻找的东西。 我找不到任何我所需要的东西。

Sub Add_Plus() Dim r As Range With Selection For Each r In Selection r.Value = "+" & r.Value Next End With End Sub 

双编辑 –

你们真棒! 我们非常接近,我只需要macros在每个单元格中为每个单词添加+号,除了指定为例外。 非常感谢!

所以我们正在寻找的输出是这样的:

macros观前的细胞1: 快乐的狗跳跃喜悦macros观后的细胞: +快乐+狗+跳跃+快乐

这就是我理解你的问题的方法 – 除了被排除在外的单词之外,单元格中的每个单词都应该有“+”。

尝试下面的代码。 请看下面的一些评论

 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 

将被replace为:

 +do +re +mi +fa +sol +la +do place all to words skip here +do +re place all 

这可以通过一个公式轻松完成。

假设“跳过单词”位于Sheet2的A列中,则:

 =IF(COUNTIF(Sheet2!A:A,A1)=0,"+","")&A1 

会做的。

干得好。 只需使用一些逻辑来确定何时跳过单词:

 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 

select你的单元格并运行这个:

 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 

更改排除以满足您的需求。