如何修复类型不匹配错误?

时间:2014-02-14 14:08:39

标签: excel vba excel-vba userform

您好我有以下代码:

Private Sub Search_Click()
Dim Name As String
Dim f As Range
Dim r As Long
Dim ws As Worksheet
Dim s As Integer
Dim FirstAddress As String
Dim str() As String

Name = surname.Value

With ws
Set f = Range("A:A").Find(what:=Name, LookIn:=xlValues)
If Not f Is Nothing Then
With Me
    firstname.Value = f.Offset(0, 1).Value
    tod.Value = f.Offset(0, 2).Value
    program.Value = f.Offset(0, 3).Value
    email.Value = f.Offset(0, 4).Text

    SetCheckBoxes f.Offset(0, 5) '<<< replaces code below

    officenumber.Value = f.Offset(0, 6).Text
    cellnumber.Value = f.Offset(0, 7).Text
    r = f.Row '<<<<<<<<< using this to locate the row of "found"
End With
    findnext
        FirstAddress = f.Address
Do
    s = s + 1
    Set f = Range("A:A").findnext(f)
            Loop While Not f Is Nothing And f.Address <> FirstAddress
    If s > 1 Then
       Select Case MsgBox("There are " & s & " instances of " & Name, vbOKCancel Or vbExclamation Or vbDefaultButton1, "Multiple entries")

       Case vbOK
            findnext
       Case vbCancel

       End Select

    End If

Else: MsgBox Name & "Not Listed"

End If

End With

End Sub

我想使用更新按钮:

private Sub update_Click()

Dim Name As String
Dim f As Range
Dim ws As Worksheet

With ws
Set f = .Cells(r, 1)  '<<<<<<<<<<<<< Mismatch type error

    f.Value = surname.Value
    f.Offset(0, 1).Value = firstname.Value
    f.Offset(0, 2).Value = tod.Value
    f.Offset(0, 3).Value = program.Value
    f.Offset(0, 4).Value = email.Value
    f.Offset(0, 5).Value = GetCheckBoxes
    f.Offset(0, 6).Value = officenumber.Value
    f.Offset(0, 7).Value = cellnumber.Value

End With
End Sub

所以我想找到找到的单元格的行,并将所有单元格替换为文本框中写入的内容(用新信息更新以前的信息) - 但是我在set f = .cells(r, 1)我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

尝试使用全局变量r:在Dim r As Long中声明Private Sub Search_Click(),在{/ 1}} 外面使用模块最顶层的所有函数:

Public r As Long

现在,在致电Public r As Long Public Sub Search_Click() 'your code End Sub Public Sub update_Click() 'your code End Sub Search_Click之后,我会打电话给r

P.S。不要忘记从update_Click删除Dim r As Long

BTW,在您的Private Sub Search_Click()update_Click个潜点中,您尚未初始化Search_Click变量:ws。将此行更改Set ws = ThisWorkbook.Worksheets("Sheet1")添加到Range("A:A")

中的.Range("A:A")