Excel VBA:运行时错误“1004”:select范围类失败的方法

我正在编写一个macros,以便在保存在模板中的Excel工作表中工作,然后从单独的应用程序中导出到.xls或.xlsx。 该macros根据input到单元格中的数量复制两列'x'次数。

Sub Matrix_Quantity() Dim x As Integer x = ActiveWorkbook.Sheets("Inspection Sampling Matrix").Cells(11, 4) Dim n As Integer n = x - 1 For numtimes = 1 To n 'Loop by using x as the index number to make x number copies. Sheets("Inspection Report").Columns("F:G").Select Selection.Copy Selection.Insert Shift:=x1 + nToRight Next End Sub 

我遇到的问题是,当使用模板(.xlt)运行macros运行良好。 只要模板转换为.xls或.xlsx,它就会工作,并提供运行时错误。 debuggingmacros时,它突出显示

 Sheets("Inspection Report").Columns("F:G").Select 

我的感觉是,它正在寻找select.xlt工作簿中的列,但转换为.xls或.xlsx时,它仍然在寻找.xlt工作簿,我不知道如何或为什么要这样做。

当我试图运行一个脚本来拆分工作簿并将它们保存为工作簿名称的单独文件时,我收到运行时错误1004,因为我隐藏了其中一个选项卡。

确保在运行拆分工作簿脚本之前先取消所有选项卡!

您必须在不同的工作表上编写代码。

尝试写在模块中相同。

我遇到了同样的问题,simoco的回答让我走上了正轨。 这应该工作:

 Sub Matrix_Quantity() Dim n As Integer Dim numtimes As Integer n = Sheets("Inspection Sampling Matrix").Cells(11, 4) - 1 For numtimes = 1 To n Sheets("Inspection Report").Columns("F:G").Copy Sheets("Inspection Report").Columns("F:G").Insert Shift:=xlShiftToRight Next End Sub