(VBA)在EXCEL上显示随机工作表

我目前有1个excel文件打开5张,命名为Sheet1Sheet2Sheet3Sheet4Sheet5 。 因为我想在Sheet1上有一个button,所以当我按下那个button时,就像Show Me 。 该button会随机给我显示我的文件( Sheet2Sheet5 )剩余的4张中的一张。

我怎样才能做到这一点? 我在Google上做了一些研究,找不到解决scheme。

将此macros指定给您的button:

 Sub PickRandomSheet() Dim wf As WorksheetFunction Set wf = Application.WorksheetFunction Sheets("Sheet" & wf.RandBetween(2, 5)).Activate End Sub 

我没有计划发布答案,但是因为已经有答案了。 这是我的版本。

逻辑

  1. 创build一个返回2个数字之间的随机数的函数
  2. 使用该号码设置您的工作表,然后激活它

代码

 Private Sub CommandButton1_Click() Dim ws As Worksheet On Error GoTo Whoa Set ws = ThisWorkbook.Sheets(RandomNumber(5, 2)) ws.Activate LetsContinue: Exit Sub Whoa: MsgBox Err.Description Resume LetsContinue End Sub Public Function RandomNumber(ByVal MaxValue As Long, _ ByVal MinValue As Long) As Long On Error Resume Next Randomize Timer RandomNumber = Int((MaxValue - MinValue + 1) * Rnd) + MinValue End Function