【问题标题】:Dividing cells by 1000 but not the ones which contain "Sum" formula将单元格除以 1000 但不是包含“总和”公式的单元格
【发布时间】:2022-11-11 21:39:39
【问题描述】:

我正在尝试编写一个代码,它将选择中的所有单元格除以 1000,但它不会对那些有求和公式的单元格做任何事情。

我目前有这个代码,但它不起作用。我对 VBA 编码相当陌生。这里的任何建议都会非常有用。

以下步骤在选择单元格时很重要:

  1. 如果一个单元格有编号
  2. 如果单元格没有 Sum() 公式(任何其他公式都可以)

    如果满足这两个标准,则将单元格值除以 1000

    For Each cell In Selection.Cells
        If IsNumeric(cell) = False Or cell.Address = Left(ActiveCell.Formula, 5) = "=Sum(" Or cell.Address = Left(ActiveCell.Formula, 6) = "=+SUM(" Or cell.Address = Left(ActiveCell.Formula, 6) = "=-SUM(" Then
            MsgBox ("Selection either does contain numbers or has only sum formulae")
        Else
            cell.value = cell.value / 1000
        End If
    Next
    

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    不知道你想用什么来实现

    Cell.Address = Left(ActiveCell.Formula,5) = "=Sum(

    您只能将一个值与另一个值进行比较。

    我敢肯定,这里更高级的人会对我表达 if 语句的方式皱眉,但它确实有效:

    Sub divideBy1000()
        Dim formCheck As Variant
        For Each ccell In Selection.Cells
            Debug.Print (ccell.Formula)
            Debug.Print (ccell.Value)
            formCheck = InStr(ccell.Formula, "SUM(") 'This checks if SUM is in the formula and returns a value bigger than 0 if so (where it occurs in the string).
            If len(trim(ccell.value2))>0 Then
                If IsNumeric(ccell.Value) And (formCheck = Null Or formCheck = 0) Then
                'You have to use AND so none of the SUM formulas get through, no else needed this way
                    If Left$(ccell.Formula, 1) = "=" Then 'EDIT to keep your formula
                        ccell.Formula = "=(" & Right$(ccell.Formula, Len(ccell.Formula) - 1) & ")/1000"                    
                    Else
                        ccell.Value = ccell.Value / 1000
                    End If
                End If
            End If
        Next ccell
    End Sub
    

    编辑: 为空单元格添加了一个捕获,因此它们不会变为 0,并添加了 Instr 以检查 @Marcucciboy2 建议的 SUM

    【讨论】:

    • 您可以使用InStr() 使其更清晰,但不一定会改善功能
    • 一直在检查你的建议,虽然它做了它应该做的事情,但我可能还应该添加 Len(ccell) > 0 因为我注意到空单元格通过 IsNumeric()
    • 是的,如果If len(trim(ccell.value2))>0 Then ,我会把它放在最初的上面
    • 好的,干杯,根据需要调整。快速提问,您选择 value2 是否有特定原因?
    • 谢谢你也帮助我学习:)
    猜你喜欢
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2019-03-17
    相关资源
    最近更新 更多