IF单元以AND开头创建随机数

时间:2018-05-02 10:49:15

标签: excel vba excel-vba

我想创建一个sub,它确定第12列中的单元格是否以262015开头。如果它确实以此开头,它应该创建一个新的随机8位数字,以" 18"然后6个随机创建的唯一数字。

我的代码似乎没有弄清楚单元格是否以262015开头,而且我无法找到有关这些要求创建8位数字的帮助。

希望你能帮助我!

Sub Opgave8()

For i = 2 To 18288
    If Left(Worksheets("arab").Cells(i, 12), 6) = "262015" Then
        Worksheets("arab").Cells(i, 3) = "18" & studyid(6)
    End If
Next i

Function UniqueRandDigits(x As Long) As String
Dim i As Long
Dim n As Integer
Dim s As String
Do
n = Int(Rnd() * 10)
If InStr(s, n) = 0 Then
s = s & n
i = i + 1
End If
Loop Until i = x + 1

UniqueRandDigits = s
End Function

End Sub

2 个答案:

答案 0 :(得分:3)

For i = 2 To 18288
    If Left(Worksheets("Base").Cells(i, 12), 6) = "262015" Then
        Worksheets("Base").Cells(i, 3) = "18" & Randdigits(6)
    End If
Next i

Function RandDigits(x As Long) As String
Dim i As Long
Dim s As String
For i = 1 To x
    s = s & Int(Rnd() * 10)
Next i
RandDigits = s
End Function

编辑:这里所有数字都不同

Function UniqueRandDigits(x As Long) As String
Dim i As Long
Dim n As Integer
Dim s As String
Do
n = Int(Rnd() * 10)
If InStr(s, n) = 0 Then
s = s & n
i = i + 1
End If
Loop Until i = x + 1

UniqueRandDigits = s
End Function

EDIT2:这是强制所有数字不同的一个

dim n as  string
dim ok as boolean
For i = 2 To 18288
    If Left(Worksheets("Base").Cells(i, 12), 6) = "262015" Then
        ok = false
        do
        n = UniqueRandDigits(6)
            If Application.WorksheetFunction.CountIf(Worksheets("Base").Range("L2:L18288"), n) = 0 Then
                Worksheets("Base").Cells(i, 3) = "18" & n
                ok = true
            end if
        loop until ok
    End If
Next i

答案 1 :(得分:1)

使用Left功能,您需要指定String,然后指定左侧的字符数,然后检查它是否等于" 262015&#34 ;

尝试以下代码:

For i = 2 To 18288
    If Left(Worksheets("Base").Cells(i, 12), 6) = "262015" Then
        Worksheets("Base").Cells(i, 3) = "XXX"
    End If
Next i