Sub 交換_1()
Dim i As Integer, j As Integer, K As Integer, FF As Integer
Dim A As Single, b As Integer
Dim L() As Integer, M() As Integer, n1() As Integer
Dim n As Integer, s As Integer, d As Integer, num1 As Integer, num2 As Integer
n = 3 ' 產品數
d = 8 '需求點
s = 4 '供幾點
num1 = s
num2 = (n * d) + 1
ReDim L(num1), M(num2), n1(num2) 'L 列數 ,M 行數 ,N new列數
For i = 1 To num1
Sheets(5).Cells(i, "Z") = Application.Sum(Range(Sheets(5).Cells(i, 1), Sheets(5).Cells(i, num2)))
Next i
For j = 1 To num2
Sheets(5).Cells(5, j) = Application.Sum(Range(Sheets(5).Cells(1, j), Sheets(5).Cells(num1, j)))
Next j
For i = 1 To num1
L(i) = Sheets(5).Cells(i, "Z") / 2
Next i
For j = 1 To num2
M(j) = Sheets(5).Cells(5, j) / 2
Next j
For i = 1 To num1
For j = 1 To num2
If Sheets(5).Cells(i, j) = 1 Then
If L(i) <> 0 Then
If M(j) <> 0 Then
Randomize
A = Rnd
If A > 0.5 Then
Sheets(5).Cells(i + 9, j) = 1
L(i) = L(i) - 1
M(j) = M(j) - 1
If L(i) = 0 Then
Exit For
End If
End If
End If
End If
End If
If j = num2 Then 'J為最後一行
For FF = 1 To num2 '總行數
n1(i) = Application.CountIf(Range(Sheets(5).Cells(i + 9, j + 1), Sheets(5).Cells(i + 9, j)), 1)
If n1(i) <> Sheets(5).Cells(i, "Z") / 2 Then
If L(i) <> 0 Then
If M(j) <> 0 Then
Sheets(5).Cells(i + 9, j) = 1
L(i) = L(i) - 1
M(j) = M(j) - 1
If L(i) = 0 Then
Exit For
End If
Else
j = j - FF
End If
End If
End If
Next FF
End If
Next j
Next i