Excel VBA代码报错:Sub or Function not defined,求修复WBS判断逻辑
修复WBS层级处理VBA代码的"Sub or Function not defined"错误
问题背景
列B中,数值代表WBS层级,文本“Activity”代表活动。代码逻辑是针对每个WBS层级,判断其覆盖的子项范围是否全为数值(无活动),若是则在该行相邻单元格写入“H”(隐藏),否则写入“K”(保留)。但执行If Application.WorksheetFunction.And(IsNumber(Range("B" & FRR & ":B" & LRR)))时,触发“Sub or Function not defined”错误。
错误原因
IsNumber是Excel工作表函数,VBA中没有这个内置函数,应该用VBA自带的IsNumeric;WorksheetFunction.And无法直接接收一个单元格范围的判断结果,这种写法逻辑本身不成立。
修复方案
替换出错的判断逻辑,改用CountIf统计范围内非数值的单元格数量:如果数量为0,说明全是WBS层级(数值),否则存在活动文本。同时还要处理当前WBS没有子项的边界情况,避免FRR/LRR未初始化导致的错误。
修复后的完整代码
Dim LR As Long 'Last Row Dim Leveli As Long 'WBS Level / Activity Level counter Dim Funci As Long 'WBS Range that covers all WBS and activities below a certain WBS Dim FRR As Long '1st Row of the WBS Range Dim LRR As Long 'Last Row of the WBS Range Dim MyCell As Range 'The Cell Identifying the subject WBS Level / Activity which need to determine its range 'Determining the Last Row LR = Range("B" & Rows.Count).End(xlUp).Row 'Determine the 1st & last rows for the range covered by each WBS level For Leveli = 3 To LR Set MyCell = Range("B" & Leveli) If IsNumeric(MyCell.Value) Then '初始化FRR和LRR,处理无子女项的情况 FRR = 0 LRR = 0 For Funci = Leveli + 1 To LR If Range("C" & Funci).Value > Range("C" & Leveli).Value Then LRR = Funci FRR = Leveli + 1 Else Exit For End If Next Funci '判断子项范围是否全为WBS层级 If FRR > 0 And LRR > 0 Then '统计范围内非空单元格数量与数值单元格数量,相等则全为数值 If Application.WorksheetFunction.CountIf(Range("B" & FRR & ":B" & LRR), "<>""""") = Application.WorksheetFunction.Count(Range("B" & FRR & ":B" & LRR)) Then MyCell.Offset(0, 2).Value = "H" Else MyCell.Offset(0, 2).Value = "K" End If Else '没有子项,直接标记为"H" MyCell.Offset(0, 2).Value = "H" End If End If Next Leveli
关键修复点
- 初始化
FRR和LRR为0,避免当前WBS没有子项时,未赋值的变量导致范围引用错误; - 用
CountIf结合Count判断:Count统计范围内数值单元格数量,CountIf(..., "<>""""")统计非空单元格数量,两者相等说明所有非空单元格都是数值; - 去掉错误的
IsNumber和WorksheetFunction.And组合,改用VBA和工作表函数兼容的写法。
内容的提问来源于stack exchange,提问作者Sherif Saleh
相关产品推荐
相关产品推荐

