Microsoft Excel VBA宏正在使Excel崩溃

Microsoft Excel VBA宏正在使Excel崩溃,vba,excel,Vba,Excel,由于某种原因,下面的宏在我的Excel完成时正在崩溃。工作簿将保存,并将删除我要求它保存的工作表。然后它崩溃Excel并询问是否要重新启动它。偶然有什么想法吗?这里的概念是,我们将excel链接到一个数据立方体,并希望创建一个仅包含值的值副本,而不包含链接到数据库的公式 Sub CreateVC() 'Set file path & target file name. Make sure you update the department within the file 'name in

由于某种原因,下面的宏在我的Excel完成时正在崩溃。工作簿将保存,并将删除我要求它保存的工作表。然后它崩溃Excel并询问是否要重新启动它。偶然有什么想法吗?这里的概念是,我们将excel链接到一个数据立方体,并希望创建一个仅包含值的值副本,而不包含链接到数据库的公式

Sub CreateVC()
'Set file path & target file name. Make sure you update the department within the file
'name in cell H2. I.E. change "Reporting - Rampage VC.xlsm" to "Reporting - VAD VC.xlsm"

Dim WBFile As Range
Set WBFile = ActiveSheet.Range("H2")

'Save current workbook
ActiveWorkbook.Save

'Save your workbook as a new file with the name at the end of the filepath in cell H2

ActiveWorkbook.SaveAs (WBFile)

'Moves your view to the first tab, Cognos Parameters in this case. It then moves to the next
'tab, copies the entire page, and does a paste as values. The loop will continue until the
'worksheet index # equals the total number of worksheets (it hits the last worksheet).
Worksheets(1).Select
 Do While ActiveSheet.Index <> Worksheets.Count
 ActiveSheet.Next.Select
 Cells.Select
 Selection.Copy
 Selection.PasteSpecial Paste:=xlPasteValues
 ActiveSheet.Range("H6").Select
 Loop

'Delete the first tab, Cognos Parameters, as it is not used in the value copy. This is also
'a safeguard from creating another VC by deleting the button linked to the macro.

Worksheets(1).Delete

'Save the new VC file that has been created.

ActiveWorkbook.Save

End Sub

谢谢

可能它崩溃了,因为您没有限定循环中的对象,如下所示

With ActiveSheet
    Do While .Index <> .Worksheets.Count
         .Next.Select
         .Cells.Select
         .Selection.Copy
         .Selection.PasteSpecial Paste:=xlPasteValues
         .Range("H6").Select
     Loop
End With

您还应该尽量不要使用Select和ActiveSheet。

我认为您不能总是保证您的Cognos参数工作表是工作表数组中的第一个。如果您的工作表名为Cognos Parameters,则使用该名称专门访问它。也不确定将单元格从一个工作表复制到另一个工作表的意义。始终将单元格从一个工作表粘贴到下一个工作表将覆盖目标工作表上存在的任何内容。当我正确看到这一点时,请再看一看,此工作表1.Delete会删除原始工作表而不是副本,因为该函数是在原始工作表中调用的。试着调试它并告诉我们,它到底在哪一行崩溃。@Alex我的格式不正确吗?这是我发布的第一个问题。它删除的是副本上的工作表,而不是原件上的工作表。宏按预期工作,删除工作表,然后Excel抛出错误。我没有调试的选项,因为VBA宏一直工作到完成。这是excel错误异常偏移量:8BFF590异常代码:c0000005异常数据:00000008。我试过用谷歌搜索它,但找不到解决办法。@PeterT这就是宏的意图。一个副本只是源工作表中的值。当我们更新链接到多维数据集的实时版本的信息时,我们希望将更新的值转储到值副本中,这样您就不必链接到多维数据集来查看数据。如果每个数据工作表都覆盖了以前的数据,那么为什么不循环到最后一秒?工作表并复制数据一次?或者干脆删除所有其他旧的工作表,并保留最后一个最新的数据?
ActiveWorkbook.SaveAs WBFile