VBA 中的公式有问题

Issue with formula in VBA

我有一个宏,它识别 B 列中的第二个可见单元格与 B 列中的所有其他可见单元格之间的值差异。然后宏 returns 我在第二个可见单元格中的值差异K 列中的单元格(在本例中为屏幕截图 52479,85 EUR)…

我希望宏通过将找到的差值(在本例中为 52479,85)添加到 B 列最后一个单元格中的现有值(在本例中为 556,32)来自动分配它。

为了做到这一点:我在代码末尾添加了这一行:Range("B" & LastRow).Formula = Range("B" & LastRow).Value + Range( "K" & secondRow).Value 但是它不起作用,宏不会将 52479 添加到 B 列最后一个单元格中的 556,32。

非常感谢您的帮助。 哈维

Sub differencetoassign()
Dim i As Long, counter As Long
Dim LastRow As Long
Dim secondcell As Range
Dim r As Range
Set r = ActiveCell
Dim secondRow As Long
LastRow = ActiveSheet.Range("B" & Rows.Count).End(xlUp).Row
Range("B1").Activate
    For i = 2 To LastRow 'assuming a header row not to be counted
If r.Rows(i).EntireRow.Hidden = False Then counter = counter + 1
        If counter = 2 Then
            Set third secondcell= r.Cells(i, "A")
            Exit For
        End If
    Next i
Debug.Print secondcell
Debug.Print LastRow
secondRow = secondcell.Row
Debug.Print secondRow
Range("B" & LastRow).Formula = Range("B" & LastRow).Value + Range("K" & secondRow).Value
End Sub

这是解决您的问题的另一种方法,效率更高且失败的可能性更小:

Option Explicit
Sub differencetoassign()

    Dim LastRow As Long
    Dim MainValue As Double 'second visible cell on column B
    Dim SubstractValue As Double 'will be summing the visible cells on column B after the second
    Dim AddValue As Double 'last visible value on column B
    Dim OutPutValue As Range
    Dim C As Range 'when looping through cells, For Each is the fastest option

    'Using with will allow you to reference a sheet so doesn't matter where you run the macro
    'the macro will only change that sheet
    With ThisWorkbook.Sheets("MySheet").AutoFilter.Range 'Change MySheet for the name of your working sheet
        AddValue = .Range("B" & .Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row).End(xlDown) 'now we have the value you want to add
        MainValue = .Range("B" & .Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row) 'the main value
        Set OutPutValue = .Range("K" & .Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row) 'where we will put the output
    End With

    'Now the substract values
    With ThisWorkbook.Sheets("MySheet")
        LastRow = .Cells(.Rows.Count, 2).End(xlUp).Row 'Last row on filtered data
        For Each C In .Range("B2:B" & LastRow).SpecialCells(xlCellTypeVisible) 'loop only through visible cells
            If Not C = MainValue Then 'We don't want the main value to be added here, so we use this to skip it
                SubstractValue = SubstractValue + C
            End If
        Next C
    End With

    'Finally we put the value
    OutPutValue.Value = MainValue - SubstractValue + AddValue   

End Sub