简体   繁体   English

在Excel VBA中,如何从加载项到活动工作簿运行工作表事件

[英]In Excel VBA, how to run a worksheet event from add-in to active workbook

I like to run code from an Excel add-in to the active workbook (xlsx). 我喜欢从Excel加载项运行代码到活动工作簿(xlsx)。 The code should apply some formatting to the active cell of the active workbook, when activated in the menu. 当在菜单中激活代码时,该代码应将某些格式应用于活动工作簿的活动单元格。

How can I achieve this? 我该如何实现?

Normally you can realize this by using the worksheet_change event in the active workbook, but this requires: 通常,您可以通过使用活动工作簿中的worksheet_change事件来实现此目的,但这需要:

  • a macro-enabled workbook, AND 启用宏的工作簿,以及
  • having the code in this particular workbook. 在此特定工作簿中具有代码。

I like to have this applied via an add-in, independent of the workbook and thus without the need to insert code in this workbook and to make this a xlsm workbook first. 我喜欢通过独立于工作簿的加载项来应用此方法,因此无需在此工作簿中插入代码,并且无需首先将其制作为xlsm工作簿。

You can catch WorksheetChange events from one worksheet in another (class) module, but in this case you probably rather use Application.SheetChange as above (code in ThisWorkbook module in addin): 您可以从另一个(类)模块中的一个工作表中捕获WorksheetChange事件,但是在这种情况下,您可能宁愿使用上面的Application.SheetChange (插件中ThisWorkbook模块中的代码):

'Create an object to catch events
Dim WithEvents ExcelApp As Excel.Application

'Assign object when addin opens
Private Sub Workbook_Open()
    Set ExcelApp = Application
End Sub

'Handle sheet changes in all workbooks
Private Sub ExcelApp_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Dim rng As Range
    'Do some validation...
    If Sh.Parent.Name = "Book1" And Sh.Name = "Sheet1" Then
        'Ensure correct range
        'Note: changes may occur in many cells at a time (delete, paste, ...)
        Set rng = Intersect(Target, Workbooks("Book1").Worksheets("Sheet1").Range("A1:B2"))
        If Not rng Is Nothing Then
            rng.Interior.ColorIndex = vbRed 'Example
        End If
    End If
End Sub

谢谢你们,似乎我可以在这里进行测试并尝试新的见解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM