2016-11-23 146 views
0

我有這樣的代碼:VBA代碼在所有工作簿時

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,但它仍然無法工作,爲什麼?

+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

+0

它不工作,檢查我的大後 – Sam

+0

什麼是在應用層面看錯誤,您需要在子 –

+0

中使用wb not activeworkbook,但仍然無法正常工作,這些代碼應放在個人文件,ThisWorkBook或某個模塊中? – Sam

相關問題