我在不同的单元格中填写了不同单词的表格
例如:
Word1 Word2 Word3 Word1 Word4
Word1 Word2 Word1 Word4
我需要一个公式/宏来替换两个相同的给定单词之间的单词,即
Word1 Word2 Word3 Word1 Word4将替换为
Word1 Word1 Word1 Word1 Word4
(对于上面的内容,我们在找到它的整行中用Word1替换了Word2,Word3)
Word1 Word2 Word1 Word3将被替换为
Word1 Word1 Word1 Word4
如果您需要更多详细信息,请与我们联系。
谢谢!
答案 0 :(得分:0)
我在你提供的两种情况下基于下面的代码,即如果在word1之间有word2改变它,如果在word1之间有word2和word3(我假设它们按顺序排列,并且总是在两个单元格中间word1)改变它们。
由于缺乏信息,该方法有点粗糙,但我知道您可能无法为了保密目的而分享更多信息。
Private Sub sub1()
Dim rng As Range
Dim word1 As String, word2 As String, word3 As String
Dim word4 As String, word5 As String, word6 As String
Set rng = Application.InputBox("Input the range you want to substitute", "Input", Type:=8)
word1 = "WordInCell1"
word2 = "WordInCell2"
word3 = "WordInCell3"
word4 = "WordInCell4"
word5 = "WordInCell5"
word6 = "WordInCell6"
For Each c In rng
With c
If .Value = word1 Then
'Check for first case
If .Offset(0, 2).Value = word1 Then
'Check if the word in between the two words1 is word2
If .Offset(0, 1).Value = word2 Then
.Offset(0, 1).Value = word1
End If
'Check for second case
ElseIf .Offset(0, 3).Value = word1 Then
'Check if the two words in between are word2 and word3 - assuming they always come in that order
If .Offset(0, 1).Value = word2 And .Offset(0, 2).Value = word3 Then
.Offset(0, 1).Value = word1
.Offset(0, 2).Value = word1
End If
Else
'Do Nothing
End If
End If
End With
Next c
End Sub
答案 1 :(得分:0)
这是针对您的问题的更通用的解决方案,无需对您正在寻找的字符串进行硬编码。
Private Sub replaceWords()
Dim rng, currentRow As Range
Dim currentCol, firstCol, lastCol As Integer
Dim word1 As Variant
Dim i, j As Integer
Set rng = Application.InputBox("Input the range you want to substitute", "Input", Type:=8)
'Disect the range into column numbers
firstCol = rng.Column
lastCol = rng.Cells.SpecialCells(xlCellTypeLastCell).Column
'Iterate through all rows
For Each currentRow In rng.Rows
currentCol = firstCol 'start at the left side of the range
While currentCol < lastCol
'Set word1 to the value of the cell in the currenct column
word1 = Cells(currentRow.Row, currentCol).Value
'Check subsequent columns for the same cell
For i = currentCol + 1 To lastCol
If Cells(currentRow.Row, i).Value = word1 Then
'If same word1 is found, fill cells in between with word1
For j = currentCol + 1 To i - 1
Cells(currentRow.Row, j) = word1
Next j
'Continue search at the column where word1 was last encountered position
currentCol = i - 1 '-1 becaus we add 1 again at the end of the while loop
Exit For
End If
Next i
currentCol = currentCol + 1 'go to next column
Wend
Next
End Sub
这将从左到右工作,所以&#34; Word1 Word2 Word1 Word2&#34;将成为&#34; Word1 Word1 Word1 Word2&#34;而不是&#34; Word1 Word2 Word2 Word2&#34;。如果您想要反过来调整代码,那就太难了。