我有一列包含这样的字符串:
ABCDEFG
ACDEF
ACDEFG
ACFG
ACDEFG
我想在包含这些字符的多个字符串中交换2个字符。这些行是随机选择的。例如,我需要将A和C交换为3行(这些行是随机选择的)。预期输出为:
CBADEFG
CADEF
ACDEFG
ACFG
CADEFG
最佳答案
VBA的方法是:
随机选择行(50/50)
检查交换前是否存在“ A”和“ C”字符
仅交换第一次出现
码
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