vba Excel 宏“运行时错误 '1004”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11746478/
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 13:40:49  来源:igfitidea点击:

Excel macro "Run-time error '1004"

excel-vbavbaexcel

提问by Kiranshell

I am new to scripting and I am trying to improve a existing Macro. I recorded a macro to remove dupliate and added it in a Main function which calls some other functions, but I am getting this error when I add the macro I recorded: Run-time error '1004': Application-defined or object-defined error.

我是脚本的新手,我正在尝试改进现有的宏。我录制了一个宏以删除重复项并将其添加到调用其他一些函数的 Main 函数中,但是当我添加我录制的宏时出现此错误:运行时错误“1004”:应用程序定义或对象定义错误.

The code looks like

代码看起来像

Sub Main()
Call DuplicateRemove
Call DeleteBlankRows
Call TrimText
End 

Sub DeleteBlankRows()
.
.
End Sub

Sub TrimText()
.
.
End Sub

Sub DuplicateRemove()
Columns("A:A").Select
ActiveSheet.Range("$A:$A678").RemoveDuplicates Columns:=1, Header:=xlNo
End Sub

Thanks, Kiran

谢谢,基兰

回答by Siddharth Rout

There is nothing wrong with your code. You will only get this error if the Activeworksheet is password protected.

您的代码没有任何问题。如果Active工作表受密码保护,您只会收到此错误。

Also it is a much better option to avoid using .Selectand ActiveSheet. Your code can be written as

此外,避免使用.Selectand也是一个更好的选择ActiveSheet。你的代码可以写成

Sub DuplicateRemove()
    Dim ws As Worksheet

    Set ws = Sheets("Sheet1")

    With ws
        If .ProtectContents = True Then
            MsgBox "Worksheet is protected"
            .Unprotect "MYPASSWORD"
            .Range("$A:$A678").RemoveDuplicates Columns:=1, Header:=xlNo
            .Protect "MYPASSWORD"
        Else
            .Range("$A:$A678").RemoveDuplicates Columns:=1, Header:=xlNo
        End If
    End With
End Sub

FOLLOWUP

跟进

Sub DuplicateTest()
    ActiveSheet.Columns(1).RemoveDuplicates Columns:=1, Header:=xlNo
End Sub

回答by sylvie

This error occur if The Microsoft Visual Basic Applications copies and pastes whole row in an Excel 2003 workbook or this error may be occur if the Microsoft copies and pastes a range of 2,516 rows or more rows in an Excel 2003 workbook at this cases runtime error1004 occurs. To get solution of this error save the workbook and manipulate the code of the macro in which you can save workbook.

如果 Microsoft Visual Basic 应用程序在 Excel 2003 工作簿中复制并粘贴整行,则会出现此错误,或者如果 Microsoft 在这种情况下在 Excel 2003 工作簿中复制并粘贴 2,516 行或更多行的范围,则可能会出现此错误 运行时错误1004发生。要解决此错误,请保存工作簿并操作可以在其中保存工作簿的宏代码。

回答by LOZ

ActiveSheet.Range("A1:C100").RemoveDuplicates Columns:=Array(1,2), Header:=xlYes

ActiveSheet.Range("A1:C100").RemoveDuplicates Columns:=Array(1,2), Header:=xlYes

Here is info I found about your situation, I hope it is helpful.

以上是我找到的关于你的情况的信息,希望对你有帮助。