如何解决types不匹配错误?

嗨,我有以下代码:

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 

我想要使​​用更新button:

 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 

所以我想findfind的单元格的行,并取代所有的单元格写入文本框(更新以前的信息与新的信息) – 但是我得到一个错误设置f = .cells(r,1)如何我能解决这个问题吗?

尝试使用全局variablesr :而不是在Private Sub Search_Click()声明Dim r As Long ,使用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之后,会被inizialized,然后你可以调用update_Click

PS不要忘记从Private Sub Search_Click()删除Dim r As Long

顺便说一句,在您的update_ClickSearch_Click潜艇你还没有初始化wsvariables: Set ws = ThisWorkbook.Worksheets("Sheet1") 。 在.Range("A:A")将此行更改Range("A:A").Range("A:A")