Excel VBA中Columns().Find()读取表单输入时无法匹配User ID的问题
问题:Excel VBA中表单输入的Double类型UserID无法通过Find方法匹配
熟练掌握MATLAB,但刚接触Excel VBA,遇到以下问题:编写CheckWaiver子程序,在BBgrade工作表第4列查找Double类型的UserID,根据对应行第7列值设置WaiverStatus。磁条读卡器读取并转Double的UserID调用时正常,但通过表单txtID控件转Double后调用,无法找到对应UserID,怀疑类型问题但无法定位。另外,同一Columns(4).Find(UserID...)在其他函数中对两种输入方式均正常工作。
相关代码
CheckWaiver子程序
Sub CheckWaiver() Set gradeSheet = ThisWorkbook.Sheets("BBgrade") ' Sheet where grades will be stored. Set foundBBp = gradeSheet.Columns(4).Find(What:=UserID, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows) 'foundBBp = Application.VLookup(UserID, gradeSheet.ListObjects("tblBBGrades").DataBodyRange, 4, False) 'If Not IsError(foundBBp) Then If Not foundBBp Is Nothing Then BBrow = foundBBp.Row If gradeSheet.Cells(BBrow, 7).Value = 1 Then WaiverStatus = True Else WaiverStatus = False MsgBox "We were unable to locate a valid Liability Waiver, please see a student worker" End If Else WaiverStatus = False MsgBox "We were unable to find your User ID in our system, please see a student worker." End If End Sub
磁条读取正常的调用代码
magData = ws.Range("A1").Value ' Read first cell of mag data, and split into usable info. Dim Arr() As String Arr = Split(magData, "^") UserName = Arr(1) UserID = CDbl(Left(Right(Arr(2), 8), 7))
表单输入异常的调用代码
UserName = txtName UserID = CDbl(txtID)
解决思路
- 排查浮点精度差异:表单输入的字符串转Double时,可能因数字长度或格式问题产生微小精度误差(比如工作表中是
1234567,表单转换后是1234567.0000001)。建议改用CLng(若UserID为整数)转换,或在Find时将双方转为字符串匹配:' 表单调用时修改转换方式 UserID = CLng(txtID) ' 或修改Find的匹配值 Set foundBBp = gradeSheet.Columns(4).Find(What:=CStr(UserID), LookIn:=xlValues, LookAt:=xlWhole) - 调整Find的匹配模式:当前使用
LookAt:=xlPart可能导致部分匹配,若工作表中UserID是纯数字,改为xlWhole精确匹配,同时确认LookIn:=xlValues是否适用(若单元格是公式结果,可尝试xlFormulas)。 - 验证变量传递正确性:在
CheckWaiver开头添加Debug.Print UserID,对比两种调用方式下传入的UserID值是否一致,排查是否存在变量作用域冲突或值被覆盖的情况。 - 用VLookup交叉测试:启用注释中的VLookup代码,若VLookup能找到结果,说明Find的参数设置存在问题;若VLookup也找不到,则可确定是类型不匹配导致的问题。
内容的提问来源于stack exchange,提问作者Peter Bohn
相关产品推荐
相关产品推荐

