为visual basic中的excel单元分配随机值

时间:2015-01-04 20:56:50

标签: vb.net

我尝试在使用字符串构建器的visual basic中使用随机函数,但它为每个单元重复相同的值...我需要所有单元格不同。

我试图说的是......

    Dim validchars As String = "abcdefghijklmnopqrstuvwxyz"
    Dim sb As New StringBuilder()
    Dim rand As New Random()
    For i As Integer = 1 To 12
        Dim idx As Integer = rand.Next(0, validchars.Length)
        Dim randomChar As Char = validchars(idx)
        sb.Append(randomChar)
    Next i
    txtPass.Text = sb.ToString
    If txtPass.Text.Length > 1 Then
        Dim newvar As String
        newvar = txtPass.Text
    End If

我需要使用这段代码为excel单元格分配大约1000个单元格的值。

1 个答案:

答案 0 :(得分:0)

由于您要输出到Excel,只需让Excel处理随机字符生成。

下面会在4x4网格中创建随机字符串(A-Z,10个字符长):

Dim excelRandomChar As String = "CHAR(RANDBETWEEN(65, 90))"
Dim numberOfChars As Integer = 10

' Write generation formula to Excel (replace with your Excel objects).
xlObject.Sheet.Range("A1:D4").FormulaR1C1 = "=" & _
    String.Join(" & ", Enumerable.Repeat(excelRandomChar, numberOfChars).ToArray)