从2个工作表中添加一系列单元格

时间:2018-04-16 19:25:57

标签: excel vba

我有一个工作代码,允许我在文件夹和数据透视表中添加所有工作表,总结一个库存表单。我现在的任务是尝试创建一个运行的总页面,我们可以在其中添加第二个工作表,只需添加或减去总行中输入的项目数。我将这段代码拼凑在一起,这在我所需要的程度上起作用。

Dim Add As Integer
Dim var1 As Integer
Dim var2 As Integer
var1 = Worksheets("Sheet1").Range("D6").Value
var2 = Worksheets("add").Range("F6").Value
Add = var1 + var2
Worksheets("Sheet1").Range("D6").Select
ActiveCell.FormulaR1C1 = Add
Application.DisplayAlerts = False
Sheets("add").Select
ActiveWindow.SelectedSheets.Delete
Sheets("Sheet1").Select

但这仅适用于单个单元格,我需要它才能在Sheet1上的D4到D649范围内工作。我不能为我的生活想到解决方案,我似乎找不到参考多张纸和多个单元格的解决方案。

3 个答案:

答案 0 :(得分:0)

也许你在此之后:

Dim i As Long
With Worksheets("Sheet1")
    For i = 4 To 649
        .Cells(i, 4) = .Cells(i, 4) + Worksheets("add").Cells(i, 6)
    Next
End With 

或者

Dim i As Long
Dim sht1Vals As Variant, shtAddVals As Variant

sht1Vals = Worksheets("Sheet1").Range("D4:D649").Value
shtAddVals = Worksheets("add").Range("F4:F649").Value
For i = 1 To 646
    sht1Vals(i, 1) = sht1Vals(i, 1) + shtAddVals(i, 1)
Next
Worksheets("Sheet1").Range("D4:D649").Value = sht1Vals

答案 1 :(得分:0)

我为你的代码添加了一个循环,看它是否有效:

Sub Macro7()

Dim Add As Integer
Dim var1 As Integer
Dim var2 As Integer
var1 = Worksheets("Sheet1").Range("D6").Value
var2 = Worksheets("add").Range("F6").Value
Add = var1 + var2

t = 6

Do Until t = 649

Worksheets("Sheet1").Cells(t, 4).Select
Selection.FormulaR1C1 = Add
Application.DisplayAlerts = False
Sheets("add").Select
ActiveWindow.SelectedSheets.Delete
Sheets("Sheet1").Select

t = t + 1

Loop

End Sub

答案 2 :(得分:0)

它与DisplayName的代码完美配合,非常感谢你。

Dim i As Long
With Worksheets("Sheet1")
For i = 4 To 649
    .Cells(i, 4) = .Cells(i, 4) + Worksheets("add").Cells(i, 6)
Next
End With