VBA / Excel-将工作表复制到另一个工作簿(替换现有值)

时间:2018-11-29 12:56:43

标签: excel vba

我试图将值从一张纸复制到另一张工作簿纸。但是我无法让Excel将值实际粘贴到其他工作簿中。

这是我的代码。

Sub ReadDataFromCloseFile()
    On Error GoTo ErrHandler
    Application.ScreenUpdating = False

    Dim src As Workbook ' SOURCE
    Dim currentWbk As Workbook ' WORKBOOK TO PASTE VALUES TO

    Set src = openDataFile
    Set currentWbk = ActiveWorkbook

     'Clear existing data
     currentWbk.Sheets(1).UsedRange.ClearContents

     src.Sheets(1).Copy After:=currentWbk.Sheets(1)

    ' CLOSE THE SOURCE FILE.
     src.Close False  ' FALSE - DON'T SAVE THE SOURCE FILE.
     Set src = Nothing

ErrHandler:
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

下面是函数openDataFile,该函数用于获取源Workbok(文件对话框):

Function openDataFile() As Workbook
'
Dim wb            As Workbook
Dim filename      As String
Dim fd            As FileDialog

Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Select the file to extract data"

' Optional properties: Add filters
fd.Filters.Clear
fd.Filters.Add "Excel files", "*.xls*" ' show Excel file extensions only

' means success opening the FileDialog
If fd.Show = -1 Then
    filename = fd.SelectedItems(1)
End If

' error handling if the user didn't select any file
If filename = "" Then
    MsgBox "No Excel file was selected !", vbExclamation, "Warning"
    End
End If

Set openDataFile = Workbooks.Open(filename)

End Function

当我尝试运行Sub时,它会打开src文件,并在那里停下来。没有值被复制并粘贴到我的currentWbk

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

也许我的潜艇会帮助你

Public Sub CopyData()
    Dim wb As Workbook
    Set wb = GetFile("Get book") 'U need use your  openDataFile  here
    Dim wsSource As Worksheet
    Set wsSource = wb.Worksheets("Data")'enter your name of ws

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets.Add

    wsSource.Cells.Copy ws.Cells
    wb.Close False

End Sub