The passage that you mentioned is confusing to many people. If we take a look at the passage these people whom Christ are talking to are professed Christians. These people claim that they have done many wonderful things in Christ's name, but it is worth while to note Christ's response to these individuals "And then I will profess unto them, I never knew you: depart from me, ye that work iniquity." We have to understand what iniquity is. According to the Strong's #458 it states; (1) the condition of without law; (A) because ignorant of it (B) because of violating it (2) contempt and violation of law, iniquity, wickedness.
In the NKJ version Matt 7:23 states "worker of lawlessness." 1John 3:4 Whosoever committeth sin transgresseth the also the law: for sin is the transgression of the law. Now I have said all that to say these people claiming to do all in the name of the Lord where lacking in some point, Christ states that they were working iniquity or lawlessness and if sin is the transgression of the law they were simply breaking the 10 commandments. Remembering James 2:10 "Whosoever shall keep the whole law, and yet offend in one point, he is guilty of all." See also Matt 5:19
1John 2:3,4 " And hereby we do know that we know him (Jesus), if we keep His commandments. He that saith, I know him, and keepeth not his commandments, is a liar, and the truth is not in him." We make claims to be true Christians, but Christ said if you are breaking my commandments I will not know you. We see this same example in the parable of Matt 25 concerning the 10 virgins. All the virgins slept and were invited to the marriage. All invited were Christians, but yet 5 refused to get more oil for their lamps.
This is however not a matter of works! We can not keep the commandments of God, unless Christ is abiding in us. 2Cor 3:18 We become changed by beholding Jesus. The works are not something we do at all, actually they are the manifestation of Christ abiding in YOU. The law has no power to save; it simply shows the true character of each person and where they are standing in relation to God. It is only a mirror showing our inner person. Who will live in your life?? Jesus Christ or Satan? Only you can answer this question. We have no power to conquer sin, we must allow Christ to live in us and we must die carnally (our natural sinful characters). This is what Jesus said, We must live by faith. Grace is extended to us an invitation to accept Jesus as our Lord and savior and be come born again not to live in the old man but by faith as a new man. The works will come as Christ lives in you for they are His works not yours!