我有一個包含這樣的字符串列:交換2個字符
ABCDEFG
ACDEF
ACDEFG
ACFG
ACDEFG
我想換2個字符的數量的字符串包含這些字符。行是隨機選擇的。例如,我需要在3行中交換A和C(行隨機選擇)。預期的輸出是:
CBADEFG
CADEF
ACDEFG
ACFG
CADEFG
我有一個包含這樣的字符串列:交換2個字符
ABCDEFG
ACDEF
ACDEFG
ACFG
ACDEFG
我想換2個字符的數量的字符串包含這些字符。行是隨機選擇的。例如,我需要在3行中交換A和C(行隨機選擇)。預期的輸出是:
CBADEFG
CADEF
ACDEFG
ACFG
CADEFG
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
你除了1和1c更多 - 即你需要限制更換單掉呢? – brettdj