基于日期的变量列

时间:2017-11-14 21:49:00

标签: vba date variables

VBA noobie在这里。

我有一个电子表格,其中包含垂直收银人列表和水平每月的每一天。即:

11/1/2017    11/2/2017    11/13/2017

Jesse

Frank

Jessica

Martin

电子表格的其余部分填充了每位收银员的销售数据。

我想随机选择5个收银员,并在单独的表格上显示他们的名字和销售数据。

我编写的代码将选择5个随机名称,但我希望将其设置为动态,以便用户可以选择运行宏的列(即,他们可以选择哪个日期)。

`Sub PickNamesAtRandom()

Dim HowMany As Integer
Dim NoOfNames As Long
Dim RandomNumber As Integer
Dim Names() As String 'Array to store randomly selected names
Dim i As Byte
Dim CellsOut As Long 'Variable to be used when entering names onto worksheet
Dim ArI As Byte 'Variable to increment through array indexes

Application.ScreenUpdating = False

HowMany = Range("C43").Value
CellsOut = 6

ReDim Names(1 To HowMany) 'Set the array size to how many names required
NoOfNames = Application.CountA(Range("A:A")) - 1 ' Find how many names in the list
i = 1

Do While i <= HowMany
RandomNo:
    RandomNumber = Application.RandBetween(2, NoOfNames + 1)
    'Check to see if the name has already been picked
    For ArI = LBound(Names) To UBound(Names)
        If Names(ArI) = Cells(RandomNumber, 1).Value Then
            GoTo RandomNo
        End If
    Next ArI
    Names(i) = Cells(RandomNumber, 1).Value ' Assign random name to the array
    i = i + 1
Loop

'Loop through the array and enter names onto the worksheet
For ArI = LBound(Names) To UBound(Names)

    Cells(CellsOut, 4) = Names(ArI)
    CellsOut = CellsOut + 1

Next ArI

Application.ScreenUpdating = True

End Sub`

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

您可以使用InputBox来获取用户想要使用的列。

Dim lRet As Long
lRet = clng(Inputbox("Select column"))

然后您可以在代码中使用该变量。改变你的位置:

Cells(RandomNumber, 1).Value 

对此:

Cells(RandomNumber, lRet).Value 

编辑: 您还需要更改此行:

NoOfNames = Application.CountA(Range("A:A")) - 1 

我建议添加一个将数字转换为字母的函数: Function to convert column number to letter?

Function Col_Letter(lngCol As Long) As String
Dim vArr
vArr = Split(Cells(1, lngCol).Address(True, False), "$")
Col_Letter = vArr(0)
End Function

您的行应更改为:

NoOfNames = Application.CountA(Range(Col_Letter(lRet) & ":" & Col_Letter(lRet))) - 1