I made a Command Button in Excel with the code

Private Sub CommandButton1_Click(ByVal Target As Range)

Dim a As Integer
Dim z As Integer
Dim q As Integer


If Target.Address = "$F$2" Then
  z = z + 1
  q = 0
End If

If z = 1 Then
  ActiveSheet.PrintOut preview:=True
  If q = 0 Then
    a = MsgBox("?????", vbYesNo)
    If a = vbNo Then
      Cancel = True
    Else: ActiveSheet.PrintOut preview:=True
    End If
  End If
End If
End Sub

and I'm getting this

enter image description here

What do I do?


The error message is correct : Procedure declaration does not match description of event.

The CommandButton control VBA event routine does not have parameters. It should be:

 Private Sub CommandButton1_Click ()
  • The error will then ly with If Target.Address = "$F$2" Then – PeterH Feb 13 at 12:02
  • 1
    All Target references will cause errors - this isn't the way to use a command button. My above link contains an example that may help. – harrymc Feb 13 at 12:08
  • I will take read on my lunch break – PeterH Feb 13 at 12:37
  • @harrymc i understand, but how do i make the code here work then? – anne Feb 13 at 13:01
  • 2
    See for example this article that may answer your question. I would like to help, but some study is still required. Posting too many questions here you risk moderator intervention. There exist an enormous amount of information about VBA, google is your friend. Some known websites are site1, site2 and site3. – harrymc Feb 13 at 13:18

You have a Command Button with a parameter of Target. This is something that is not possible, and as such you are getting an error.

You have to remove that part, and aquire the selected cell using worksheet.activecell instead, or selection.target. But it has been a while since I did VBA coding and I currently don't have VBA handy, so I cannot provide the correct code right now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.