Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

vba - Excel macro "Run-time error '1004"

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.

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$1:$A$95678").RemoveDuplicates Columns:=1, Header:=xlNo
End Sub

Thanks, Kiran

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

Sub DuplicateRemove()
    Dim ws As Worksheet

    Set ws = Sheets("Sheet1")

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

FOLLOWUP

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...