以“=xxx+xxx...”的形式生成总和

Generate Sum Total in form of "=xxx+xxx..."

我对以下代码有疑问 - 它无法生成“=XXX+XXX+XXX+XXX”(XXX = 数字)的结果 有什么问题吗?

有3个部分 A 部分:正确添加注释 <---运行 B 部分:将 username/editor 的名字添加到注释 <---运行 中 C 部分:显示总和,但形式为“=xxx+xxx+xxx+xxx”而不是“=Sum(yyy:zzz)”<--无错误但无结果

F 列是总和,第 9 行是项目名称,范围 I10 到最后一行和最后一列是 table,但最后一行和最后一列是可变的

Option Explicit

Public Sub AddComments()

    Dim ws As Worksheet: Set ws = ActiveSheet 'sheet select
    
    Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, "F").End(xlUp).Row
    Dim lCol As Long: lCol = ws.Cells(9, ws.Columns.Count).End(xlToLeft).Column
    Dim srg As Range: Set srg = ws.Range("A1").Resize(lRow, lCol) 'Used area
    Dim Data As Variant: Data = srg.Value 'value in used area
    Dim r As Long, c As Long, n As Long
    Dim Comm As String
    Dim fitcomment As Comment
    
    For r = 22 To lRow
        For c = 9 To lCol
            If Len(Data(r, c)) > 0 Then
                n = n + 1
                Comm = Comm & n & ". " & Data(9, c) & " -" _
                   & Format(Data(r, c), "$#,##0") & vbLf
            End If
        Next c
        If n > 0 Then
            With srg.Cells(r, 6)
                .ClearComments
                .AddComment Left(Comm, Len(Comm) - 1)
            End With
            n = 0
            Comm = ""
        End If
    Next r

    For Each fitcomment In Application.ActiveSheet.Comments 'Add User Name
        fitcomment.Text Text:=Environ$("Username") & vbLf, Start:=1, Overwrite:=False
        fitcomment.Shape.TextFrame.Characters(1, Len(Environ$("UserName"))).Font.Bold = True
        fitcomment.Shape.TextFrame.AutoSize = True
    Next


    For r = 22 To lRow
        c = 9
        Comm = "="
        Do
            If ws.Cells(r, c).Value <> "" And IsNumeric(ws.Cells(r, c)) And ws.Cells(r, c).Value <> 0 Then
                Comm = Comm & "+" & ws.Cells(r, c).Value
            End If
            c = c + 1
        Loop While Not (c > ws.UsedRange.Columns.Count)
        If Comm <> "=" Then
            ws.Cells(6, r).Value = Comm
        Else
            ws.Cells(6, r).Value = ""
        End If
    Next r
    
    MsgBox "Comments added.", vbInformation
    
End Sub

看起来您在编写 Comm 结果时已经为 ws.Cells 调换了 row/column 参数。

代码正在生成一个公式字符串,但它被写入从第 22 列开始的第 6 行 ('V')。单元格 V6 可能超出了您显示器上显示的列 - 这解释了为什么它 看起来 好像没有输出。

   If Comm <> "=" Then
        ws.Cells(6, r).Value = Comm
    Else
        ws.Cells(6, r).Value = ""
    End If

应该是:

   If Comm <> "=" Then
        ws.Cells(r, 6).Value = Comm
    Else
        ws.Cells(r, 6).Value = ""
    End If

顺便说一句,您生成的总和 String 的格式为“=+XXX+XXX+XXX”。 Excel 正在为您修正为“=XXX+XXX+XXX”。