VBA代码适用于所有工作簿

时间:2016-11-23 12:01:21

标签: vba excel-vba excel

我有这段代码:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

Lastrow = ActiveSheet.Cells(Rows.Count, 12).End(xlUp).Row       

If ActiveWorkbook.Name Like "FR_*" And WorksheetFunction.CountIf(ActiveSheet.Range(Cells(4, 12), Cells(Lastrow, 12)), "<>Pending Distribution") > 0 Then
    MsgBox "Warning, column L has values other than Pending Distribution"
    Cancel = True
End If

End Sub

它在vba中保存到工作簿中时有效,但它在Personal.xlsb中不起作用

我想让它在所有以FR_开头的工作簿上运行,但是尽管我使用的是ActiveSheet和ActiveWorkbook,它仍无法正常工作,为什么?

1 个答案:

答案 0 :(得分:1)

使用这样的个人应该有帮助

Public WithEvents CUSTOM_EXCEL As Excel.Application

Private Sub CUSTOM_EXCEL_WorkbookBeforeSave(ByVal Wb As Workbook, ByVal SaveAsUI As Boolean, Cancel As Boolean)
Lastrow = Wb.ActiveSheet.Cells(Rows.Count, 12).End(xlUp).Row
If Wb.Name Like "FR_*" And WorksheetFunction.CountIf(Wb.ActiveSheet.Range(Cells(4, 12), _
    Cells(Lastrow, 12)), "<>Pending Distribution") > 0 Then
    MsgBox "Warning, column L has values other than Pending Distribution"
    Cancel = True
End If
End Sub

Private Sub Workbook_Open()
    Set CUSTOM_EXCEL = Application
End Sub

enter image description here