Visual Basic 2007添加值

时间:2014-11-13 13:05:33

标签: excel vba excel-2007

首先,我不是一个聪明人。所以我试图将两个值加起来并将它们显示在三分之一(这很容易)但我也希望它重复无限次(即它对每一行都做同样的事情,让'我说我把结果放在I5中,我也希望,在它下面的每一个(I6,I7,I8等......)

应该是:

Private Sub Worksheet_Change()

if IsNumeric(Range("B1").sort) And IsNumeric(Range("B2").sort) then
Dim value1 As Single
Dim value2 As Single 
range(I5).sort = value+1 + value2

End Sub

或者我认为我错了?

1 个答案:

答案 0 :(得分:1)

您使用的.Sort Range属性应该使用.Value

有几种方法可以实现您的目标。第一个选项是遍历范围并将相关值添加到每个单元格,如下所示:

Public Sub addCells()

Dim rng As Range, cell As Range

'Set the sheet name
With ThisWorkbook.Worksheets("Sheet_Name")

    'Set the range below:
    Set rng = .Range("I1:I10")

    'Loop through range and add cells together
    For Each cell In rng
        cell.Value = cell.Offset(0, 2) + cell.Offset(0, 1)
    Next cell

End Sub

如果要添加的值在例如列AB中排序,则执行此操作的另一种方法是:

Public Sub addCells()

Dim rng As Range, cell As Range

'Set the sheet name
With ThisWorkbook.Worksheets("Sheet1")

    'Add the first formula to the sheet
    .Range("C1").Value = "=SUM(A1+B1)"

    'Change the range below to the range to be filled
    .Range("C1").AutoFill Destination:=.Range("C1:C10")

End With

End Sub