将代码复制到新创建的工作簿的ThisWorkbook模块(VBA)

时间:2018-07-01 00:56:33

标签: excel vba excel-vba

我有一个宏,可以创建5个新工作簿并向其中填充一些信息。我想确保最终用户使用默认文件名保存创建的工作簿。为此,我编写了一个工作簿事件代码,该事件代码在保存文件时运行,并自动填充文件名字段。

this.geolocation.getCurrentPosition({enableHighAccuracy: false, timeout: 3000, maximumAge: 100000}).then((resp) => {
   this.userLocation.lat = resp.coords.latitude;
   this.userLocation.lng = resp.coords.longitude;
   this.getLocation();
}).catch((error) => {
  this.geolocation.getCurrentPosition({enableHighAccuracy: true, timeout: 3000, maximumAge: 100000}).then((resp) => {
     this.userLocation.lat = resp.coords.latitude;
     this.userLocation.lng = resp.coords.longitude;
     this.getLocation();
  }).catch((error) => {
    this.userLocation.lat = this.userData.location.lat || 0;
    this.userLocation.lng = this.userData.location.lng || 0;
    //if fails, get users last known location.
    this.getLocation();
    console.log('Error getting location', error);
  });
  console.log('Error getting location', error);
});

这与我想要的完全一样,但是我希望能够将这些代码放入使用VBA创建的所有5个工作簿的Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Set Wb = ThisWorkbook Application.EnableEvents = False Co = ThisWorkbook.Sheets(1).Name If InStr(1, Wb.Name, Co) = 0 Then Filename = Co & " " & Format(Now, "yyyy-mm-dd") With Application.Dialogs(xlDialogSaveAs) Call .Show(Filename, xlOpenXMLWorkbookMacroEnabled) End With Else Wb.Save End If Application.EnableEvents = True Cancel = True End Sub 模块中。

有没有办法完成这项任务?

2 个答案:

答案 0 :(得分:1)

是的。在VBA中,您需要添加对Microsoft Visual Basic For Applications Extensibility 5.3(或您拥有的任何版本)的引用。在对象浏览器中,您会注意到一个名为VBIDE的新库。

您将需要在Trust Center...Macro Settings中更改“开发人员Marco设置”,以选中"Trust access to the VBA object model."

一个很好的示例摘要是here.

答案 1 :(得分:0)

尝试此代码

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim wb          As Workbook
Dim ws          As Worksheet
Dim co          As String
Dim fn          As String

Set wb = ThisWorkbook

Application.EnableEvents = False
    For Each ws In ThisWorkbook.Worksheets
        co = ws.Name
        If InStr(1, wb.Name, co) = 0 Then
            fn = co & " " & Format(Now, "yyyy-mm-dd")
            With Application.Dialogs(xlDialogSaveAs)
                Call .Show(fn, xlOpenXMLWorkbookMacroEnabled)
            End With
        Else
            wb.Save
        End If
    Next ws
Application.EnableEvents = True
Cancel = True
End Sub