2015-04-17 68 views
0

我想要一個vba代碼,其中所有行都包含值1..n(n從屬於txt文件)只有一次。一些單元格已經從txt文件中獲得了值。 這是我做的,但它不給我,我想:如何在1..n範圍內使用不同的隨機數在1到n範圍內使用vba代碼

Function randomnum(n As Integer, ProbMatrix() As Integer) As Integer 
Dim k As Integer, newvalue As Integer 
    newvalue = Int(n * Rnd + 1) 
    For i = 1 To n 
     For k = 1 To n 
      If ProbMatrix(i, k) = newvalue Then 
       newvalue = RandInt(n) 
       k = 0 
      End If 
     Next k 
      randomnum = newvalue 
    Next i 
End function 
+0

你的意思是你想要1和n之間的整數的整數?如果是這樣,然後執行此操作:http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle – Bathsheba

+0

它給你什麼?它在我看來,如果你的'ProbMatrix(i,k)= newvalue'在某種程度上有點擊球,你會得到一個接近無限循環,因爲你重置'k = 0''side_'For K = 1。 ..'循環。 – FreeMan

+0

在程序中,用戶可以選擇三個示例問題文件之一。每個示例問題文件都包含n x n個數組中的一些值。第一列是示例文件中的數字n。首先,我們必須將給定的值顯示在正確的位置,然後用範圍(1-n)中的隨機數填充行,以便所有行都精確地包含值1,...,n。 –

回答

0

這裏是A1並運行一個單細胞,細胞A1

放置一個值的示例子程序()產生隨機號碼的列表中的相鄰小區:

Sub Routine() 
    Dim i As Long, MMX As Long 
    MMX = Range("A1").Value 
    ReDim ary(1 To MMX) As Variant 

    For i = 1 To MMX 
     ary(i) = i 
    Next i 

    Call Shuffle(ary) 

    For i = 1 To MMX 
     Cells(1, 1 + i).Value = ary(i) 
    Next i 

End Sub 

Sub Shuffle(InOut() As Variant) 
    Dim HowMany As Long, i As Long, J As Long 

    Hi = UBound(InOut) 
    Low = LBound(InOut) 
    ReDim Helper(Low To Hi) As Double 
    Randomize 

    For i = Low To Hi 
     Helper(i) = Rnd 
    Next i 


    J = (Hi - Low + 1) \ 2 
    Do While J > 0 
     For i = Low To Hi - J 
      If Helper(i) > Helper(i + J) Then 
      Temp = Helper(i) 
      Helper(i) = Helper(i + J) 
      Helper(i + J) = Temp 
      Temp = InOut(i) 
      InOut(i) = InOut(i + J) 
      InOut(i + J) = Temp 
      End If 
     Next i 
     For i = Hi - J To Low Step -1 
      If Helper(i) > Helper(i + J) Then 
      Temp = Helper(i) 
      Helper(i) = Helper(i + J) 
      Helper(i + J) = Temp 
      Temp = InOut(i) 
      InOut(i) = InOut(i + J) 
      InOut(i + J) = Temp 
      End If 
     Next i 
     J = J \ 2 
    Loop 
End Sub 

例如:

enter image description here

相關問題