如何绕过"宏被禁用"消息并让宏运行Workbook_Activate?

时间:2016-12-21 23:55:30

标签: excel vba excel-vba

我有一些VBA代码可以在激活工作簿/工作表时格式化/调整屏幕大小。

代码如下:

Private Sub Workbook_Activate()
  Dim SaveSelection As Object
  Set SaveSelection = Selection
  Application.ScreenUpdating = False
  Range("A1:T50").Select
  ActiveWindow.Zoom = True
  Application.DisplayFullScreen = False
  Application.DisplayFormulaBar = False
  ActiveWindow.DisplayWorkbookTabs = True
  ActiveWindow.DisplayHeadings = False
  ActiveWindow.DisplayGridlines = False
   Range("A1:T50").Select
  ActiveWindow.Zoom = True
  On Error GoTo ExitPoint
  SaveSelection.Select
  Application.ScreenUpdating = True
ExitPoint:
End Sub

此处的问题是,当用户首次打开工作簿时,他们会收到此安全警告消息"宏已被禁用",因此当用户首次打开工作簿时宏不会运行,因为该消息出现。

有没有人知道这方面的解决方法?

2 个答案:

答案 0 :(得分:3)

通常可以通过在Trusted Locations中添加工作簿的文件夹路径来解决此问题。

答案 1 :(得分:2)

正如sigil所指出的,将文件的文件夹位置添加到受信任位置将阻止显示Enable Macros.vbs对话框。

或者,您可以创建一个VBScript文件来打开工作簿。

  • 将此功能粘贴到NotePad中
  • 调整FILE_NAME常量
  • 按住 Ctrl + S
  • 单击[另存为类型]
  • 选择所有文件(
  • 使用Const FILE_NAME = "C:\Excel FIles\Hello World.xlsm" Dim oExcel On Error Resume Next Set oExcel = GetObject(, "Excel.Application") On Error Goto 0 If TypeName(oExcel) = "Empty" Then Set oExcel = WScript.CreateObject("Excel.Application") oExcel.Visible = True oExcel.Workbooks.Open FILE_NAME 作为其扩展程序保存文件
Sub FBA_test_1()

Dim products As Variant
Dim productsWithParams As Variant
LastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

'products = Array("one", "two", "three")
products =Workbooks("sourceFile.xlsx").Worksheets("Sheet1").Range("A2:A4").Value

'productsWithParams = Array(Array("one", 10, 11), Array("two", 20, 21), Array("three", 30, 31))
productsWithParams = Workbooks("sourceFile.xlsx").Worksheets("Sheet1").Range("A2:C4").Value

For x = LastRow To 1 Step -1

    ' if value not found inside the array using the "MATCH" function
    pos = Application.Match(Range("$A$" & x).Value, products, 0)
    If IsError(pos) Then
        Range("$B$" & x).Value = "ERROR - "
    Else ' successful "MATCH" inside the array
        Range("$B$" & x).Value = pos
        Range("$C$" & x).Value = products(pos, 1) 'name
        Range("$D$" & x).Value = productsWithParams(pos, 2) 'param1
        Range("$E$" & x).Value = productsWithParams(pos, 3) 'param2

   End If
Next
End Sub