当用户从我的加载项选项卡中按下按钮时,会触发以下代码:
Sub OnActionListaMarkowitz(control As IRibbonControl)
GeneratesWorkbook
End Sub
在不同的模块中,我有一个sub来创建一个新的工作簿,并将我的Xlam文件中的工作表复制到新的工作簿。
Sub GeneratesWorkbook()
On Error GoTo LabelErro
Set PlanilhaMarkowitz = Workbooks.Add
Dim currentSheet As Worksheet
Dim sheetIndex As Integer
sheetIndex = 1
'Changes xlam property to false so I can copy Xlam sheets to new wb
ThisWorkbook.IsAddin = False
ThisWorkbook.Activate
'Copy Xlam's sheets to new workbook
Sheets("Hidden").Visible = True 'this workbook was very hidden so I make it visible to copy
Sheets("Hidden").Copy Before:=PlanilhaMarkowitz.Sheets(sheetIndex)
Sheets("Hidden").Visible = xlVeryHidden
Sheets("Calculos").Copy Before:=PlanilhaMarkowitz.Sheets(sheetIndex)
Sheets("Pesos").Copy Before:=PlanilhaMarkowitz.Sheets(sheetIndex)
Sheets("Atributos").Visible = True 'this workbook was very hidden so I make it visible to copy
Sheets("Atributos").Copy Before:=PlanilhaMarkowitz.Sheets(sheetIndex)
Sheets("Atributos").Visible = xlVeryHidden
Sheets("Correl").Copy Before:=PlanilhaMarkowitz.Sheets(sheetIndex)
Sheets("Fronteira").Copy Before:=PlanilhaMarkowitz.Sheets(sheetIndex)
ThisWorkbook.IsAddin = True
Exit Sub
LabelErro:
ThisWorkbook.IsAddin = True
End Sub
奇怪的是,如果我通过按F8执行此代码(一步一步)它完美地工作。但是,如果我正常运行此代码或使用F5,它只复制工作表(“隐藏”)。
我在
处设置了一个断点Sheets("Hidden").Visible = True
按F8直到两个潜艇的末端使其工作。按F5不会。
答案 0 :(得分:1)
不要依赖.Activate。将工作表复制到新工作簿的操作是更改活动工作簿。
Sub GeneratesWorkbook()
On Error GoTo LabelErro
Dim PlanilhaMarkowitz As Workbook
Set PlanilhaMarkowitz = Workbooks.Add
Dim currentSheet As Worksheet
Dim sheetIndex As Integer
sheetIndex = 1
With ThisWorkbook
'Changes xlam property to false so I can copy Xlam sheets to new wb
.IsAddin = False
'Copy Xlam's sheets to new workbook
.Sheets("Hidden").Visible = True 'this workbook was very hidden so I make it visible to copy
.Sheets("Hidden").Copy Before:=PlanilhaMarkowitz.Sheets(sheetIndex)
.Sheets("Hidden").Visible = xlVeryHidden
.Sheets("Calculos").Copy Before:=PlanilhaMarkowitz.Sheets(sheetIndex)
.Sheets("Pesos").Copy Before:=PlanilhaMarkowitz.Sheets(sheetIndex)
.Sheets("Atributos").Visible = True 'this workbook was very hidden so I make it visible to copy
.Sheets("Atributos").Copy Before:=PlanilhaMarkowitz.Sheets(sheetIndex)
.Sheets("Atributos").Visible = xlVeryHidden
.Sheets("Correl").Copy Before:=PlanilhaMarkowitz.Sheets(sheetIndex)
.Sheets("Fronteira").Copy Before:=PlanilhaMarkowitz.Sheets(sheetIndex)
.IsAddin = True
End With
Exit Sub
LabelErro:
ThisWorkbook.IsAddin = True
End Sub
有关远离依赖选择和激活以实现目标的更多方法,请参阅How to avoid using Select in Excel VBA macros。