相同代码在不同用户窗体上的工作方式不同

时间:2019-05-21 07:29:42

标签: excel vba

我已经创建了一个用户表单,用于记录和检索有关正在测试的引擎的数据。对于一种引擎,代码工作正常,而对于另一种引擎,我遇到了问题。两者之间的唯一区别是存储数据的页面的名称,对于正常工作的页面是DW10数据,对于不正常的页面是XUD9数据。它将写入XUD9数据并从中检索数据没有问题,但是它不允许我进行更新,因此它不能是工作表的名称,因为没有一种用户窗体可以正常工作。

XUD9用户窗体与DW10用户窗体完全相同,它是一个副本,只是名称引用已更改。

Private Sub confirmupdate_Click()

Dim Rerow As Range

Set Rerow = Worksheets("DW10 Data").Range("H:H").Find(Codetext, searchdirection:=xlPrevious)


Worksheets("DW10 Data").Cells(Rerow.Row, 2).Value = Rigtext2.Text
Worksheets("DW10 Data").Cells(Rerow.Row, 4).Value = Serialtext2.Text
Worksheets("DW10 Data").Cells(Rerow.Row, 5).Value = Hourstext2.Text
Worksheets("DW10 Data").Cells(Rerow.Row, 3).Value = CDbl(CDate(Datetext2))
Worksheets("DW10 Data").Cells(Rerow.Row, 6).Value = parttext2.Text
Worksheets("DW10 Data").Cells(Rerow.Row, 7).Value = commentstext2.Text
Worksheets("DW10 Data").Cells(Rerow.Row, 8).Value = codetext2.Text

confirmupdate.Visible = False

End Sub

Private Sub confirmupdate_Click()

Dim Rerow As Range

Set Rerow = Worksheets("XUD9 Data").Range("H:H").Find(Codetext, searchdirection:=xlPrevious)


Worksheets("XUD9 Data").Cells(Rerow.Row, 2).Value = Rigtext2.Text
Worksheets("XUD9 Data").Cells(Rerow.Row, 4).Value = Serialtext2.Text
Worksheets("XUD9 Data").Cells(Rerow.Row, 5).Value = Hourstext2.Text
Worksheets("XUD9 Data").Cells(Rerow.Row, 3).Value = CDbl(CDate(Datetext2))
Worksheets("XUD9 Data").Cells(Rerow.Row, 6).Value = parttext2.Text
Worksheets("XUD9 Data").Cells(Rerow.Row, 7).Value = commentstext2.Text
Worksheets("XUD9 Data").Cells(Rerow.Row, 8).Value = codetext2.Text

confirmupdate.Visible = False

End Sub

我在XUD9版本上收到的错误消息基本上是Rerow is Nothing,因此它显然找不到Codetext值来返回它要查找的行,但是DW10在完全相同的代码下可以正常工作。

我明显缺少什么吗?我是VBA的新手,而且自学成才(谷歌是您的朋友),因此可能很简单。

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码来确保所需的内容出现在表格中。

Option Explicit
Public Rerow As Range

Sub test(ByVal wsName As String, strCodeText As String)

    With ThisWorkbook.Worksheets(wsName)

        Set Rerow = .Range("H:H").Find(strCodeText, searchdirection:=xlPrevious)

        If Not Rerow Is Nothing Then
            .Cells(Rerow.Row, 2).Value = Rigtext2.Text
            .Cells(Rerow.Row, 4).Value = Serialtext2.Text
            .Cells(Rerow.Row, 5).Value = Hourstext2.Text
            .Cells(Rerow.Row, 3).Value = CDbl(CDate(Datetext2))
            .Cells(Rerow.Row, 6).Value = parttext2.Text
            .Cells(Rerow.Row, 7).Value = commentstext2.Text
            .Cells(Rerow.Row, 8).Value = codetext2.Text
        Else
            MsgBox strCodeText & " not appears in column H"
        End If

    End With

    confirmupdate.Visible = False

End Sub

Private Sub confirmupdate_Click()

    Dim Codetext As String

    Codetext = "Test" 'Change the Codetext to what you are looking for
    Call Module1.test("DW10 Data", Codetext)

    Codetext = "Test2" 'Change the Codetext to what you are looking for
    Call Module1.test("XUD9 Data", Codetext)


End Sub