VBA中使用名称的Index Match函数报错,请求代码协助
排查VBA代码中
Index/Match行的错误 先聚焦你标注的这行错误代码:
ws.Range("D" & yrow).Value = Application.WorksheetFunction.Index(harga, Application.WorksheetFunction.Match(ComboBox3, koin, 0)).Value
这里存在几个典型问题,我帮你逐一分析并给出修复方案:
多余的
.Value后缀:Application.WorksheetFunction.Index本身就会返回匹配单元格的值,末尾额外添加.Value属于语法冗余,会触发编译错误,直接去掉即可。未处理匹配失败的异常:如果
ComboBox3的内容在koin范围中找不到对应项,WorksheetFunction.Match会直接抛出运行时错误。建议改用Application.Match(不带WorksheetFunction前缀),它在匹配失败时会返回错误值,我们可以提前做错误判断:Dim matchPos As Variant matchPos = Application.Match(ComboBox3, koin, 0) If IsError(matchPos) Then MsgBox "Tidak dapat menemukan item koin yang sesuai!" Exit Sub End If确认
harga和koin的有效性:要确保这两个变量是正确定义的工作表范围对象——如果是命名范围,需确认它们存在且指向正确区域;如果是自定义变量,要提前用Set语句赋值(比如Set koin = Sheets("Data").Range("A1:A20")),否则会触发“变量未定义”或“对象变量未设置”的错误。
修复后的BELI分支代码片段
If (ComboBox1.Value = "BELI") Then If (ComboBox3 = "" Or ComboBox5 = "" Or ComboBox6 = "") Then MsgBox ("Masih ada kolom yg belum di isi") Exit Sub Else ws.Range("A" & yrow).Value = "=ROW()-1" ws.Range("B" & yrow).Value = Sheets("TRX").Range("B2") ws.Range("C" & yrow).Value = ComboBox3 ' 优化后的Index/Match逻辑 Dim matchPos As Variant matchPos = Application.Match(ComboBox3, koin, 0) If IsError(matchPos) Then MsgBox "Tidak dapat menemukan item koin yang sesuai!" Exit Sub End If ws.Range("D" & yrow).Value = Application.Index(harga, matchPos) End If End If
额外建议:在代码开头添加Option Explicit语句,强制所有变量声明,能有效避免因拼写错误导致的隐性问题。
内容的提问来源于stack exchange,提问作者Yan LimaBenua
相关产品推荐
相关产品推荐

