【问题标题】:Excel VBA: Run-time error '1004': Select method of Range class failedExcel VBA:运行时错误“1004”:范围类的选择方法失败
【发布时间】:2015-06-11 00:51:13
【问题描述】:

我正在编写一个宏以在 Excel 工作表中工作,该工作表保存在模板中,然后从单独的应用程序导出为 .xls 或 .xlsx。此宏用于根据输入到单元格中的数量复制两列“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) 运行宏时,它运行良好。一旦模板转换为 .xls 或 .xlsx,它就会发现工作并给出运行时错误。调试宏时它会突出显示

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

我的感觉是它正在寻找 .xlt 工作簿中的列,但是当转换为 .xls 或 .xlsx 时,它仍在尝试寻找 .xlt 工作簿,我不确定它是如何或为什么这样做的这个。

【问题讨论】:

  • 这是因为您的工作表 Inspection Report 在宏运行时未处于活动状态。请阅读how to avoid using Select/Active statements。你可以用Sheets("Inspection Report").Columns("F:G").CopySheets("Inspection Report").Columns("F:G").Insert Shift:=x1 + nToRight替换你的代码
  • 感谢您的回复。当我插入您推荐的代码并运行宏时,Excel 将崩溃且没有错误。它只是提出了 Windows 错误“Microsoft Excel 已停止工作”
  • 其实,我不明白你在这里做什么:Shift:=x1 + nToRight?应该是Shift:=xlToRight

标签: vba excel


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    尝试在 Module 中编写相同的内容。

    【讨论】:

    • 我添加了以下行:code sheet.Activate (Where sheet is the Worksheet I'm using) sheet.Range("A1").Select code 它消除了错误。 Excel 在继续之前切换到工作表一秒钟,这很烦人,但没什么大不了的。
    【解决方案3】:

    我遇到了同样的问题,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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      相关资源
      最近更新 更多