Excel VBA宏父子关系判定求助:基于缩进值匹配目标列
基于Excel单元格缩进值判定父子关系(P/C)的VBA逻辑问题
我已编写Excel VBA宏,实现以下功能:
- 在B列获取A列单元格的缩进值(来自「设置单元格格式」对话框的对齐选项卡)
- 尝试在C列根据缩进值判定父子关系(标记为P/C),要求结果与D列一致,但目前逻辑存在问题
核心要求
必须基于B列的缩进值实现判定逻辑,因为A列的数值可能发生变动。
额外判定规则
若当前行缩进值小于上一行,且下一行缩进值与当前行相同,则标记为C。
现有代码
Sub GetIndentLevels() Dim ws As Worksheet Dim lastRow As Long Dim i As Long Dim rng As Range Dim indentLevel As Integer ' Set the worksheet Set ws = ThisWorkbook.Sheets("Target") ' Change "Sheet1" to your sheet name ' Find the last row with data in column A lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row ' Loop through each row in column A For i = 1 To lastRow ' Get the range for the current cell in column A Set rng = ws.Cells(i, "A") ' Get the indent level of the cell indentLevel = rng.indentLevel ' Write the indent level to column B ws.Cells(i, "B").Value = indentLevel Next i End Sub Sub DetermineParentChild() Dim ws As Worksheet Dim lastRow As Long Dim currentRow As Long Dim currentValue As Variant Dim nextValue As Variant Dim markParent As Boolean ' Set the worksheet Set ws = ThisWorkbook.Sheets("Target") ' Find the last row in column A lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row ' Initialize the markParent variable markParent = False ' Loop through each row in column A For currentRow = 1 To lastRow ' Get the value of column B for the current row currentValue = ws.Cells(currentRow, 2).Value ' Check if the current value is numeric If IsNumeric(currentValue) Then ' Check if the next row exists and get its value If currentRow < lastRow Then ' Get the value of column B for the next row nextValue = ws.Cells(currentRow + 1, 2).Value Else ' If there is no next row, set nextValue to a default value nextValue = "" End If ' Check if the current value should be marked as "P" (Parent) or "C" (Child) If markParent Then ws.Cells(currentRow, 3).Value = "P" Else If nextValue = currentValue + 1 Then ws.Cells(currentRow, 3).Value = "P" Else ws.Cells(currentRow, 3).Value = "C" End If End If ' Update the markParent variable for the next iteration markParent = (nextValue <> currentValue + 1) Else ' If the current value is not numeric, mark it as "C" (Child) ws.Cells(currentRow, 3).Value = "C" End If Next currentRow End Sub
相关截图说明
- 截图1:展示目标结果(D列)与当前C列输出的对比,标题为「ParentChild」
- 截图2:展示额外规则对应的场景示例,标题为「若当前行缩进值小于上一行且下一行与当前行缩进相同,则标记为C」
恳请各位提供帮助!
内容的提问来源于stack exchange,提问作者user7571572
相关产品推荐
相关产品推荐

