我该如何避免这种重复的代码?

时间:2016-06-22 17:53:00

标签: vba excel-vba excel

我有一堆工作表的子程序,所有子程序都以完全相同的方式开始和结束。它们基本上遍历表中的每一行,并对每一行执行一些独特的操作。我不希望它们每次都运行,而是希望能够单独调用它们。

这是实际代码的样子:

Sub randomSub()
    Dim finalRow As Long
    Dim i As Long

    finalRow = Sheet.Cells(Rows.count, Column).End(xlUp).row

    With Sheet2
        For i = 3 To finalRow
            ' Do some random operations here
        Next i
    End With
End Sub

将代码设置为循环遍历每一行并不难,但在重复4到5个不同的子代之后,我想有更好的方法。

所以我想我的问题是这样的:是否有一种最佳做法可以避免为我制作的每个新副本一遍又一遍地编写这样的循环设置?

编辑:以下是我正在进行的操作类型的一些示例,通常会替换' Do random operations here

Sub moveToFront()
    Dim stringHolder() As String

    stringHolder = Split(Sheet2.Cells(i, 11), "; ")
    If stringHolder(1) = "" Then
        .Cells(i, 11) = stringHolder(0)
    Else
        .Cells(i, 11) = stringHolder(1) & "; " & stringHolder(0)
    End If
End Sub

另一个

Sub fillInTotals()
    If .Cells(i, 3) <> "" Then
        .Cells(i, 1) = "='EUS Graph'!$C$" & _
            Application.WorksheetFunction.Match(.Cells(i, 3), Sheet4.Range("$A:$A"), 0)
    Else
        .Cells(i, 1) = "='EUS Graph'!$C$"
    End If
End Sub

1 个答案:

答案 0 :(得分:2)

考虑使用通用的用户定义函数,并将其置于所有宏都可以访问的位置,ThisWorkbook部分或标准模块:

Public Function randomSub(SheetName As String, ColumnLetter As String, _
                          OperationType As String)
    Dim wsh As Worksheet
    Dim i As Long, finalRow As Long
    Dim stringHolder() As String

    Set wsh = ThisWorkbook.Worksheets(SheetName)

    With wsh
        finalRow = wsh.Cells(wsh.Rows.Count, ColumnLetter).End(xlUp).Row
        For i = 3 To finalRow                              
             Select Case OperationType

                 Case "MoveToFront"
                    stringHolder = Split(Sheet2.Cells(i, 11), "; ")
                    If stringHolder(1) = "" Then
                        .Cells(i, 11) = stringHolder(0)
                    Else
                        .Cells(i, 11) = stringHolder(1) & "; " & stringHolder(0)
                    End If

                 Case  "fillInTotals"
                    If .Cells(i, 3) <> "" Then
                            .Cells(i, 1) = "='EUS Graph'!$C$" & _
                                     Application.WorksheetFunction.Match(.Cells(i, 3), _
                                     Sheet4.Range("$A:$A"), 0)
                    Else
                            .Cells(i, 1) = "='EUS Graph'!$C$"
                    End If

             End Select
        Next i
    End With
End Function

然后,根据需要调用函数,传递所需的参数:

Call randomSub(ActiveSheet.Name, "A", "MoveToFront")