从工作簿中求和单元格并粘贴到另一个工作簿中

时间:2018-02-16 11:54:32

标签: excel vba excel-vba

我有2个工作簿,我需要在另一个工作簿的单元格中复制2个单元格的总和。我正常地复制值,但在一种情况下,我需要复制2个单元格的总和。我尝试使用此代码,但它不起作用:

Sub Excel_Excel()
Dim x As ThisWorkbook
Dim y As Workbook
Dim Total As Double

Application.ScreenUpdating = False
Application.DisplayAlerts = False

''allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
''make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
''determine what choice the user made
If intChoice <> 0 Then
''get the file path selected by the user
    strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)

End If

'## Open workbook:
Set y = Workbooks.Open(strPath)

'Now, copy what you want from y:
y.Sheets("Deducciones").Range("F70:F86").Copy
'Now, paste to ThisWorksheet x:
ThisWorkbook.Sheets("Deducciones").Range("rngdeducciónID").PasteSpecial    xlPasteValues

'Define range that you need to sum, sum it and copy:
range1 = y.Sheets("Deducciones").Range("F87:F88")
Total = WorksheetFunction.Sum(Range(range1))
y.Sheets("Deducciones").Total.Copy
'Now, paste to ThisWorksheet x:
ThisWorkbook.Sheets("Deducciones").D86.PasteSpecial

'Close y:
y.Close

End Sub

此代码无效:Total = WorksheetFunction.Sum(Range(range1))

1 个答案:

答案 0 :(得分:0)

如下所示:

Sub Excel_Excel()
Dim x As ThisWorkbook
Dim y As Workbook
Dim Total As Double

Application.ScreenUpdating = False
Application.DisplayAlerts = False

''allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
''make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
''determine what choice the user made
If intChoice <> 0 Then
''get the file path selected by the user
    strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)

End If

'## Open workbook:
Set y = Workbooks.Open(strPath)

'Now, copy what you want from y:
y.Sheets("Deducciones").Range("F70:F86").Copy
'Now, paste to ThisWorksheet x:
ThisWorkbook.Sheets("Deducciones").Range("rngdeducciónID").PasteSpecial xlPasteValues

'Define range that you need to sum, sum it and add to variable Total:
Total = WorksheetFunction.Sum(y.Sheets("Deducciones").Range("F87:F88"))
'Now, pass the value of Total to ThisWorksheet x:
ThisWorkbook.Sheets("Deducciones").Range("D86").Value = Total

'Close y:
y.Close
End Sub