尝试将两个Select Case Functions组合成一个For Loop参数

时间:2013-09-22 02:40:36

标签: vb.net excel

在我的项目中,我有两个功能,每个功能都有3张,我已经设置为Select Case。每个功能分为3张。这些过程是较大程序的一部分,该程序将数据导入excel工作簿,然后将该数据格式化以执行某些分析。因此,在执行每个子时必须遵循一步一步的顺序。

原因是因为一张纸上发生的任何事情都必须发生在功能中的其他3张纸上。例如,如果对其进行排序,则必须对所有3进行排序。考虑到这一点,我有一个程序,自动填充B6中的一些数据:AH6在第一个函数中有三张。

这是:

    Public Function EmployeeSheets(Index As Long) As Excel.Worksheet

    'This function indexes all of the Employee sheets
    'to use in various loops during he instal process
    '@param EmployeeSheets, are the sheets to index

    Select Case Index

        Case 1 : Return xlWSAllEEAnnul
        Case 2 : Return xlWSAllEEHourly
        Case 3 : Return xlWSAllEESalary

    End Select

    Throw New ArgumentOutOfRangeException("Index")

End Function

Sub copyFormulas()

    Dim eeRefSheets As Excel.Worksheet

    For i As Long = 1 To 3 Step 1

        eeRefSheets = EmployeeSheets(i)

        With eeRefSheets
            Dim lngLr As Long

            lngLr = .Cells.Find(What:="*", SearchDirection:=Excel.XlSearchDirection.xlPrevious, SearchOrder:=Excel.XlSearchOrder.xlByRows).Row

            .Range("B6:AH6").AutoFill(.Range("B6:AH" & lngLr), Excel.XlAutoFillType.xlFillDefault)

        End With

    Next i

End Sub

那里没问题,一切顺利。除了现在我必须对这些表格做同样的事情:

Public Function PositionSheets(Index As Long) As Excel.Worksheet

'This function indexes all of the Position sheets
'to use in various loops during he instal process
'@param PositionSheets, are the sheets to index

Select Case Index

    Case 1 : Return xlWSAllPositionAnnul
    Case 2 : Return xlWSAllPositionHourly
    Case 3 : Return xlWSAllPositionSalary

End Select

Throw New ArgumentOutOfRangeException("Index")

我想做的是不是两次编写For Loop,而是将Select Case索引合并到一个循环中并执行自动填充。

可以这样做,还是有更好的方法?

1 个答案:

答案 0 :(得分:1)

尝试将其作为子..并使用Byref作为变量引用..

Public Sub EmplNPosSheets(Index As Long, ByRef ES As Excel.Worksheet, ByRef PS As Excel.Worksheet) 

    'This function indexes all of the Employee sheets
    'to use in various loops during he instal process
    '@param EmployeeSheets, are the sheets to index

    Select Case Index

        Case 1 
          ES = xlWSAllEEAnnul
          PS = xlWSAllPositionAnnul
        Case 2 
          ES = xlWSAllEEHourly
          PS = xlWSAllPositionHourly
        Case 3 
          ES = xlWSAllEESalary
          PS = xlWSAllPositionSalary

    End Select

    Throw New ArgumentOutOfRangeException("Index")

End Sub

要使用它,请这样做..

Dim eeRefSheets As Excel.Worksheet 
Dim posRefSheets As Excel.Worksheet

Set eeRefSheets = Application.Worksheets(0)
Set posRefSheets = Application.Worksheets(0)

EmplNPosSheets(i,eeRefSheets,posRefSheets)