0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Excel VBA 从某一行开始,逐行向下插入空白行,并写入随机日期

Posted at

从第二行开始,向下随机插入日期
按照千分之二的概率插入,插入行数为1-5行随机

Sub 随机插入日期()
    i = 2
    iMax1 = 1000
    iMin1 = 1
    iMax2 = 5
    iMin2 = 1
    fstDate = #1/1/2022#
    lstDate = #12/31/2025#
    Do
        ret1 = Format(Fix((iMax1 - iMin1 + 1) * Rnd + iMin1), "0")
        If ret1 = 10 or ret1 = 11 Then
            ret2 = Format(Fix((iMax2 - iMin2 + 1) * Rnd + iMin2), "0")
            For ii = 1 To ret2
                Rows(ii + 1).Insert shift:=xlShiftDown
                cells(ii + 1,"A") = CStr(Format(Int(lstDate - fstDate + 1) * Rnd + fstDate, "yyyyMMdd"))
            Next ii
        End If
        
        
        i = i + 1
        
    Loop While Cells(i, "A") <> ""
End Sub
  • ret1用于随机生成1-1000的数值,在Do-While里,如果生成的值位10或者11,则进行插入计算(千分之2的概率)
  • ret2用于随机生成1-5的插入次数,生成完成后,由下面的For进行循环插入
  • i用于记录数据处理的初始行
  • 持续循环的条件为:当前单元格不为空,即:当前单元格不为空,则进行下一次循环
  • xlShiftDown为插入方向向下
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?