Excel VBA:运行时错误“1004”:Range 类的选择方法失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22207182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:55:10  来源:igfitidea点击:

Excel VBA: Run-time error '1004': Select method of Range class failed

excelvbaexcel-vba

提问by user3384820

I am writing a macro to work in an excel sheet that is saved within a template then exported to .xls or .xlsx from a separate application. This macro is to copy two columns 'x' number of times depending on a quantity that is entered into a cell.

我正在编写一个宏以在保存在模板中的 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

The problem I am having is that when the macro is run withing the template (.xlt) it runs fine. As soon as the template is converted to .xls or .xlsx it spots working and gives a runtime error. When debugging the macro it highlights

我遇到的问题是,当宏与模板 (.xlt) 一起运行时,它运行良好。一旦模板转换为 .xls 或 .xlsx,它就会发现工作并给出运行时错误。调试宏时,它会突出显示

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

My feeling is that it is looking to select the columns in the .xlt workbook but when converted to .xls or .xlsx it is still trying to look for the .xlt workbook and I'm not sure how or why its doing this.

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

回答by Papersquid

When I tried to run a script to split workbooks and save them as separate files with their workbook names, I received runtime error 1004 because I had one of the tabs hidden.

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

Make sure you UNHIDE all tabs before running a split workbook script!

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

回答by Manu

You must be writing code on different sheet referencing different.

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

Try to write the same in Module.

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

回答by GlennFromIowa

I was having the same kind of problem and simoco's answer got me on the right track. This should work:

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