如何通过VBA为Excel中的嵌套伪代码添加缩进实现美观打印?
Excel伪代码自动缩进VBA实现
需要给Excel A列中的未缩进伪代码添加4空格缩进,支持嵌套处理IF/ELSEIF/ELSE/END、WHILE/END代码块,现有VBA代码无法实现效果,输出与输入一致,请求修改代码。
输入伪代码
WHILE TRUE DISPLAY "Welcome to Bank ATM - Cash Withdrawal" amount = INPUT "How much would you like to withdraw today?" IF (amount MOD 10) != 0 THEN DISPLAY "You can only withdraw a multiple of ten!" ELSE IF amount<10 THEN DISPLAY "You can only withdraw above of £10" ELSEIF amount>1000 THEN DISPLAY "You can only withdraw between £10 and £1000" ELSE notes20 = amount DIV 20 notes10 = (amount MOD 20) / 10 DISPLAY "Collect your money: " DISPLAY " >> £20 Banknotes: " + notes20 DISPLAY " >> £10 Banknotes: " + notes10 DISPLAY "Thank you for using this Python Bank ATM." DISPLAY "Good Bye." END END END
当前无效的VBA代码
Sub indent() a = WorksheetFunction.Transpose(Range("A1:A21")) if_count = 0 end_count = 0 For i = 1 To UBound(a) If a(i) = "IF" Then If (if_count = 0 And end_count = 0) Then Debug.Print a(i) if_count = if_count + 1 ElseIf if_count > 0 Then Debug.Print " " & a(i) if_count = 0 Else Debug.Print a(i) End If Else Debug.Print a(i) End If Next End Sub
期望格式化输出
WHILE TRUE DISPLAY "Welcome to Python Bank ATM - Cash Withdrawal" amount = INPUT "How much would you like to withdraw today?" IF (amount MOD 10) != 0 THEN DISPLAY "You can only withdraw a multiple of ten!" ELSE IF amount<10 THEN DISPLAY "You can only withdraw above of £10" ELSEIF amount>1000 THEN DISPLAY "You can only withdraw between £10 and £1000" ELSE notes20 = amount DIV 20 notes10 = (amount MOD 20) / 10 DISPLAY "Collect your money: " DISPLAY " >> £20 Banknotes: " + notes20 DISPLAY " >> £10 Banknotes: " + notes10 DISPLAY "Thank you for using this Python Bank ATM." DISPLAY "Good Bye." END END END
修改后的VBA代码
Sub IndentPseudoCode() Dim arr As Variant Dim indentLevel As Integer Dim i As Integer Dim lineText As String ' 读取A列所有非空行数据 arr = WorksheetFunction.Transpose(Range("A1", Range("A" & Rows.Count).End(xlUp))) indentLevel = 0 For i = 1 To UBound(arr) lineText = Trim(arr(i)) ' 遇到END时,先降低缩进级别再输出 If Left(lineText, 3) = "END" Then indentLevel = indentLevel - 1 Debug.Print String(indentLevel * 4, " ") & lineText Else ' 先按当前缩进输出该行 Debug.Print String(indentLevel * 4, " ") & lineText ' 判断是否需要提升缩进级别 If Left(lineText, 5) = "WHILE" Or Left(lineText, 2) = "IF" Or _ Left(lineText, 4) = "ELSE" And Not Left(lineText, 7) = "ELSEIF" Then indentLevel = indentLevel + 1 End If End If Next i End Sub
关键修改说明
- 用
indentLevel变量跟踪当前缩进层级,每级对应4个空格 - 调整处理逻辑:
- 遇到
END时,先降低缩进级别再输出该行 - 其他行先按当前缩进输出,再判断是否提升缩进:
WHILE、IF、ELSE(排除ELSEIF)触发缩进+1
- 遇到
- 支持动态读取A列所有非空行,无需硬编码行数
- 用
Trim()处理行首空格,避免影响关键词判断
内容的提问来源于stack exchange,提问作者Rasec Malkic
相关产品推荐
相关产品推荐

