随机删除MS excel表中30%的单元格数据

时间:2017-08-31 07:34:22

标签: excel vba excel-vba apache-poi

我有200行和150列(即30000个单元格)的excel表。我想随机删除30%的总数据(即从随机行和随机列中删除)。如果我可以一次从一列中随机删除30%的数据,那也应该没问题。

请建议一个宏/公式/ Java代码(使用POI),可以帮助我实现同样的目标。

提前致谢!

2 个答案:

答案 0 :(得分:0)

将= Rand()放在最后一列并将其复制下来,按大到小排序然后删除60行

答案 1 :(得分:0)

选择您要使用的范围并运行此宏,或者,如果您有固定范围,请将Set rng = Selection更改为Set rng = Range("A1:ET200")或您的范围。

Sub DelThirty()
Dim rng As Range
Dim i As Long, x As Long, y As Long

Set rng = Selection

On Error GoTo ErrHandler

Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False

For i = 1 To Int(rng.Cells.Count * 0.3)
retry:
    x = WorksheetFunction.RandBetween(1, rng.Rows.Count)
    y = WorksheetFunction.RandBetween(1, rng.Columns.Count)
    If rng.Cells(x, y) <> "" Then
        rng.Cells(x, y).ClearContents
    Else
        GoTo retry
    End If
Next i

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

ErrHandler:
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub