是否可以使用Excel VBA中的另一个宏来修改宏代码

时间:2019-04-25 07:13:33

标签: excel vba excel-vba-mac

实际上,我已经为执行相同工作的多个工作簿编写了相同的宏,从开始到现在,工作簿的增长变得太长了,即到目前为止,它已接近700+,因此,如果我需要在宏,我需要手动打开和更新所有工作簿。那么是否有解决方案可以将相同的代码更新到所有宏。

如下,

abc1.xlsm - has macro-A running
abc2.xlsm - has macro-A running
abc3.xlsm - has macro-A running
abc4.xlsm - has macro-A running
abc5.xlsm - has macro-A running
...........
abc700.xlsm - has macro-A running

所有700个文件都运行相同的宏,如果我在一个文件中说abc1.xlsm更新了宏代码,则该代码应在所有excel文件中更新。有什么解决办法吗?

2 个答案:

答案 0 :(得分:1)

Option Explicit

Sub test()

    Dim LastRow As Long

    With ThisWorkbook.Worksheets("Sheet1") 'Here you refer to the specific workbook & worksheet
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'Avoid using fix number for last row. Calculate last row using this method.
    End With

End Sub

注意:

  • with语句引用当前工作簿的第1页
  • 计算 Sheet1 当前工作簿中列 A 的最后一行。

另一种方式-呼叫功能

Option Explicit

Function Get_LastRow(ByVal ws As Worksheet, ColumnNo As Long)

    With ws
        Get_LastRow = .Cells(.Rows.Count, ColumnNo).End(xlUp).Row 'Avoid using fix number for last row. Calculate last row using this method.
    End With

End Function

Sub test()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim ColumnNo As Long, LastRow As Long

    Set wb = ThisWorkbook 'Set your workbook.
    Set wb = Workbooks("Book1") 'Another way to set workbook

    Set ws = wb.Worksheets("Sheet1") 'Set your worksheet

    ColumnNo = 1 'Set the column from where you want the last row

    LastRow = Get_LastRow(ws, ColumnNo)  'Call the function to count last row of column 1 in worksheet 1 in workbook Book1

    MsgBox LastRow

End Sub

注意:

  • 设置工作簿,工作表和ColumnNo并运行代码。您将收到一个消息框,指示最后一行。

答案 1 :(得分:1)

解决方案是将参数传递给宏,然后使用Select...Case 取决于该参数的语句。

在此语句内,您将执行不同的代码。