在打开的工作簿上运行代码而不是宏表

时间:2016-01-26 13:58:22

标签: excel vba excel-vba

目的:

在宏打开的工作簿中创建一个新工作表。

打开工作簿,但随后将工作表添加到Marco文件中,而不是我刚刚自动打开的文件。

问题:

我不确定为什么工作表“NewPortalFormula”没有添加到现在打开的工作簿中。

代码:

Dim vCheckName As String
vCheckName = Application.ActiveWorkbook.Path + "\" & objFile.Name
Set wb = Workbooks.Open(objFolder + "\" & objFile.Name)
' then activate it
wb.Activate
' Otherwise, workbook is already open, refer to it by name
'If worksheet exists delete it
Application.DisplayAlerts = False
Worksheets("NewPortalFormula").Delete
Application.DisplayAlerts = True
'Add new sheet to open workbook
wb.Activate
wb.Worksheets("NewPortalFormula").Add
wb.Save
wb.Close

1 个答案:

答案 0 :(得分:2)

Dim Ws As Worksheet

Dim vCheckName As String
vCheckName = Application.ActiveWorkbook.Path + "\" & objFile.Name

Set wb = Workbooks.Open(objFolder + "\" & objFile.Name)

Application.DisplayAlerts = False
Worksheets("NewPortalFormula").Delete
Application.DisplayAlerts = True

Set Ws = wb.Worksheets.Add
Ws.Name = "NewPortalFormula"
wb.Save
wb.Close

尽量避免使用.activate或.select。代码不需要激活与它们一起工作的东西。

从评论中添加