从另一个工作簿复制数据

时间:2015-04-29 12:20:59

标签: excel vba file

我正在尝试将文件中的当前数据替换为具有相同属性的任何其他所选文件中的数据。我想从任何其他选定文件替换当前文件中A1:Q的数据。我尝试编写代码但显示错误。

select [yearThis].[years], [yearThis].[months]
     , isnull([yearThis].[expenses], [yearLast].[expenses]) 
  from [tblact] as [yearThis] 
  left join [tblact] as [yearLast] 
    on [yearLast].[years]  = [yearThis].[yearThis] - 1 
   and [yearLast].[months] = [yearThis].[months]

1 个答案:

答案 0 :(得分:0)

这不是最漂亮的代码,但它的工作方式正如您所要求的那样!

Sub newdata()

Dim myfile As Window
Dim currentSheet As Worksheet
Dim lastRow As Double
Dim sourceFileName As String
Dim sourcefileworksheet As String
Dim destinationwb As String
Dim destinationwksheet As String
'set destination worksheet as open workbook when you run macro

destinationwb = ActiveWorkbook.Name
destinationwksheet = ActiveSheet.Name

'Select source file
Dim fNameAndPath As Variant, wb As Workbook
    fNameAndPath = Application.GetOpenFilename(Title:="Select File To Be Opened")
 ' cancel macro if nothing selected
        If fNameAndPath = False Then
        MsgBox ("Nothing Selected, Macro Cancelled")
        Exit Sub
        End If

'Open Source File.xlsx
Workbooks.Open (fNameAndPath)

'set source names
sourceFileName = ActiveWorkbook.Name
sourcefileworksheet = ActiveSheet.Name

'Determine last row of source
lastRow = Workbooks(sourceFileName).Worksheets(sourcefileworksheet).Range("A1").End(xlDown).Row

'Past the table in my current Excel file - Note that you should change the range of destination to A1:Q if you want all copied
Workbooks(destinationwb).Worksheets(destinationwksheet).Range("A1:E" & lastRow) = Workbooks(sourceFileName).Worksheets(sourcefileworksheet).Range("A1:Q" & lastRow).Value

'Close Source File.xlsx
Workbooks(sourceFileName).Close

'Confirm complete
MsgBox ("Complete!")

End Sub
相关问题