从Excel范围中select随机数

在下面的列表中,它是一个Excel范围,我需要select两个数字等于100,所以作为回报,我想得到(30&70)或(60&40)。 我可以做到这一点dynamic

我使用Excel,但如果你有任何其他程序的build议,它会没事的。

一个
三十
60
70
40

这里的代码没有validation重复对

 Sub test() Dim x&, lastR&, oCell1 As Range, oCell2 As Range, Key As Variant Dim Dic As Object: Set Dic = CreateObject("Scripting.Dictionary") x = 1 lastR = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row For Each oCell1 In ActiveSheet.Range("A1:A" & lastR) For Each oCell2 In ActiveSheet.Range("A1:A" & lastR) If oCell1.Value + oCell2.Value = 100 Then Dic.Add x, "(" & oCell1.Value & " & " & oCell2.Value & ")" x = x + 1 End If Next Next For Each Key In Dic Debug.Print Key, Dic(Key) 'output in immediate window all possible Next MsgBox Dic(WorksheetFunction.RandBetween(1, Dic.Count)) End Sub 

这里的结果

在这里输入图像说明

这里是validation重复对的代码

 Sub test() Dim x&, S$, S2$, check%, lastR&, oCell1 As Range, oCell2 As Range, Key As Variant Dim Dic As Object: Set Dic = CreateObject("Scripting.Dictionary") x = 1 lastR = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row For Each oCell1 In ActiveSheet.Range("A1:A" & lastR) For Each oCell2 In ActiveSheet.Range("A1:A" & lastR) check = 0 If oCell1.Value + oCell2.Value = 100 Then S = "(" & oCell1.Value & " & " & oCell2.Value & ")" S2 = "(" & oCell2.Value & " & " & oCell1.Value & ")" For Each Key In Dic If Dic(Key) = S Or Dic(Key) = S2 Then check = 1: Exit For End If Next If check = 0 Then Dic.Add x, S Debug.Print x, Dic(x) x = x + 1 End If End If Next Next MsgBox Dic(WorksheetFunction.RandBetween(1, Dic.Count)) End Sub 

这里的结果

在这里输入图像描述

A1A4的数据试试这个macros:

 Sub JustKeepTrying() Dim N As Long, M As Long, wf As WorksheetFunction Set wf = Application.WorksheetFunction Do N = wf.RandBetween(1, 4) M = wf.RandBetween(1, 4) If N <> M Then If Cells(M, 1) + Cells(N, 1) = 100 Then MsgBox Cells(M, 1).Address & vbTab & Cells(M, 1).Value & vbCrLf _ & Cells(N, 1).Address & vbTab & Cells(N, 1).Value Exit Sub End If End If Loop End Sub 

假设你有范围A1:a11数字0到100步10 [0,10,20,...,90,100]你可以使用这个逻辑(在这里,结果用蓝色突出显示)

 Set BaseRange = Range("A1:a11") BaseRange.ClearFormats 'first number- rundomly find With BaseRange.Cells(Int(Rnd() * BaseRange.Cells.Count) + 1) .Interior.Color = vbBlue FirstNo = .Value End With 'second number find by difference- error handling required if there is no matching value for each number BaseRange.Find(100 - FirstNo).Interior.Color = vbBlue