首页 > 解决方案 > 是否可以使用 Excel VBA 中的另一个宏修改宏代码

问题描述

实际上我已经为多个工作簿编写了相同的宏来完成相同的工作,工作簿的增长从开始到现在变得太长,即到现在已经接近 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 文件中更新该代码。有什么解决办法吗?

标签: excelvbamacos

解决方案


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
  • 计算Sheet1Current WorkbookA列的最后一行。

另一种方式 - 调用函数

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 并运行代码。您将收到一个指示最后一行的消息框。

推荐阅读