You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

设置Range时触发运行时错误9,调试高亮Set Rng语句求助

问题分析与修复方案

核心错误(Set Rng行高亮的原因)

Find方法参数里的VBA常量拼写错误:所有x1开头的常量应为xl(小写字母L,不是数字1),VBA无法识别x1Formulas这类错误常量,导致编译报错。

其他问题及修复点

  • 变量拼写错误:Promt = "" 应为 Prompt = ""(变量定义为Prompt,拼写需一致)
  • 未定义变量:Bin未声明就使用,需添加声明;且获取A列值的方式错误,不能直接用Rng.Columns("A:A"),应取当前行的A单元格值
  • 无效代码:Prompt = Prompt无实际作用,可改为提示已输入内容优化体验
  • 冗余变量:RowCrnt已定义但未使用,可删除

修复后的完整代码

Private Sub CommandButton1_Click()
    Dim Prompt As String
    Dim RetValue As String
    Dim Rng As Range
    Dim Bin As String ' 声明Bin变量

    Prompt = "" ' 修正拼写错误
    With Sheets("Bin7in")
        Do While True
            RetValue = InputBox(Prompt & "Enter Die Number")
            If RetValue = "" Then
                Exit Do
            End If

            ' 修正Find方法的常量拼写(x1改为xl)
            Set Rng = .Columns("C:C").Find(What:=RetValue, After:=.Range("C1"), _
                LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, _
                SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)

            If Rng Is Nothing Then
                MsgBox RetValue & " Not found"
            Else
                ' 获取对应行的A列单元格值
                Bin = .Cells(Rng.Row, "A").Value
                MsgBox RetValue & " In Bin " & Bin
            End If
            ' 更新Prompt,提示已处理的内容
            Prompt = RetValue & " 已处理," & vbCrLf
        Loop
    End With
End Sub

内容的提问来源于stack exchange,提问作者CSM71593

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 05:00:59