Excel VBA-从活动单元中减去变量

时间:2017-10-02 18:17:34

标签: excel vba excel-vba excel-formula subtraction

以下是代码:

Sub Minus()
Dim numsub As Integer
If (D3 <> "") Then
    numsub = Worksheets("Inventario 31-12-2015 ").Range("D3").Value
    Dim FindString As Integer
    Dim Rng As Range
    FindString = ActiveWorkbook.Worksheets("Inventario 31-12-2015 ").Range("C3").Value
        With Sheets("Inventario 31-12-2015 ").Range("C25:C")
        Set Rng = .Find(What:=FindString, _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlValues, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        End With
        If Not Rng Is Nothing Then
            Application.Goto Rng.Offset(0, 4), True
            ActiveCell.Value = ActiveCell.Value - numsub
        End If
End If
End Sub

我要做的是:找到正确的单元格(此函数应该像我已经使用的那样工作),选择它并减去D3的值。因为我对VBA很新,所以我无法让代码工作。 任何提示,反馈或评论都欢迎和赞赏。 THX

1 个答案:

答案 0 :(得分:2)

这个答案回应了上面的评论,并整理了一点。 (你的工作表名称到底有空格吗?)

FindString声明按OP建议更改。此外,我将你的Integer改为Long,这是一个很好的做法(谷歌的详细信息)。

Sub Minus()

Dim numsub As Long
Dim FindString As String
Dim Rng As Range

With Worksheets("Inventario 31-12-2015 ")
    If .Range("D3") <> vbNullString Then
        numsub = .Range("D3").Value
        FindString = .Range("C3").Value
        With .Range("C25:C100") 'change 100 to suit
            Set Rng = .Find(What:=FindString, _
                            After:=.Cells(.Cells.Count), _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlNext, _
                            MatchCase:=False)
        End With
        If Not Rng Is Nothing Then
            Application.Goto Rng.Offset(0, 4), True
            Rng.Offset(0, 4).Value = Rng.Offset(0, 4).Value - numsub
        End If
    End If
End With

End Sub