我的命令框中的编码错误 – Excel VBA

我在这里有一些代码,但我得到以下错误:

运行时错误1004

应用程序定义或对象定义的错误

所以希望有人能帮我弄清楚我做错了什么。 所有这些还是很新的

我想要我的用户表单来完成

我有一个两页的用户表单,它使用多页。

我希望所有用户都能在第一页上填写详细信息,名为“主”。 在这个表单上是一个选项button的问题:“客户今天问了一个产品吗?”。

如果这个问题的答案是“否”,那么表单应该在命令button被点击后结束,并将相关信息发送到工作表。

如果这个问题的答案是肯定的,表单应该自动发送用户到“额外”页面。 用户完成这个页面,点击第二页上的命令button,表单将把这两个页面的信息发送到工作表的同一行。

我的代码

对于“主”页面上的命令button

Private Sub CommandButton1_Click() Dim emptyRow As Long Dim closeForm As Boolean 'The form should close, unless ProductEnquiryYes is true closeForm = True 'Determine emptyRow emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1 'Did customer ask about product? If ProductEnquiryYes.Value = True Then Me.MultiPage1.Value = 1 closeForm = False Cells(emptyRow, 20).Value = 1 End If If ProductEnquiryNo.Value = True Then Cells(emptyRow, 21).Value = 1 End If 'Balance Enquiry If BalanceEnquiry.Value = True Then Cells(emptyRow, 23).Value = 1 End If 'Close Userform If closeForm Then Unload Me End Sub 

对于“额外”页面上的命令button

 Private Sub CommandButton2_Click() 'If this checkbox is True, send value of 1 to the worksheet If CAOpen.Value = True Then Cells(emptyRow, 63).Value = 1 End If Unload Me End Sub 

命令button适用于第一页,并正确返回值到工作表中。 但是,第二页上的命令button是不正确的,我不知道为什么。 这可能是明显的,所以请原谅我。

当我点击debugging时,具体是这条以黄色突出显示的行:

 Cells(emptyRow, 63).Value = 1 

谢谢您的帮助!!

其实我觉得错误是你用emptyRow

 Private Sub CommandButton2_Click() 'If this checkbox is True, send value of 1 to the worksheet If CAOpen.Value = True Then Cells(emptyRow, 63).Value = 1 End If Unload Me End Sub 

但是还没有初始化! 在CommandButton1_Click你有

 Dim emptyRow As Long 

所以emptyRow不是全局的,而是一个局部variables。

您必须重新创build并重新计算emptyRow

 Private Sub CommandButton2_Click() Dim emptyRow As Long 'Determine emptyRow emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1 'If this checkbox is True, send value of 1 to the worksheet If CAOpen.Value = True Then Cells(emptyRow, 63).Value = 1 End If Unload Me End Sub 

您可以使用Option Explicit选项更严格。