我有一个包含这样字符串的列:
ABCDEFG
ACDEF
ACDEFG
ACFG
ACDEFG
我想在包含那些字符的多个字符串中交换2个字符。行是随机选择的。例如,我需要在3行中交换A和C(随机选择行)。预期的输出是:
CBADEFG
CADEF
ACDEFG
ACFG
CADEFG
答案 0 :(得分:2)
假设你的字符串在A2:A6和行号标准在E1:G1中,那么试试这个......
在B2
=IF(ISNUMBER(MATCH(ROWS(A$2:A2),$E$1:$G$1,0)),SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A2,"C","^"),"A","C"),"^","A"),A2)
答案 1 :(得分:2)
VBA接近:
码
Sub ACDC()
Randomize
Dim X
Dim lngCnt As Long
Dim strIn As String
Dim strOut As String
strIn = "A"
strOut = "C"
X = Range([a1], Cells(Rows.Count, "A").End(xlUp)).Value2
For lngCnt = 1 To UBound(X)
If Rnd() > 0.5 Then
'check for both conditions
If InStr(X(lngCnt, 1), strIn) Then
If InStr(X(lngCnt, 1), strOut) Then
X(lngCnt, 1) = Replace(X(lngCnt, 1), strIn, "|", , 1)
X(lngCnt, 1) = Replace(X(lngCnt, 1), strOut, strIn, , 1)
X(lngCnt, 1) = Replace(X(lngCnt, 1), "|", strOut, , 1)
End If
End If
End If
Next
[b1].Resize(lngCnt - 1, 1).Value2 = X
End Sub
答案 2 :(得分:-1)
只是想想是否对任何人都有帮助。
在Excel公式中,尝试类似的操作
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A3,"A","|"),"C","A"),"|","C").
在VBA中,尝试这样的事情,
strSwap = Replace(Replace(Replace(strToSwap, "A", "|"), "C", "A"), "|", "C")