导入时忽略并覆盖现有工作表

时间:2015-10-02 08:27:23

标签: excel-vba overwrite import-from-excel vba excel

以下宏导入一个名为"已审核"从已关闭的工作簿中导入并重命名它"数据"。宏工作正常。但是,我希望宏覆盖现有的"数据"表,这是代码失败的地方。我尝试使用On error resume NeXT .. on error goto 0语句。但它刚刚添加了一张新表,并没有覆盖现有的数据"片。

Sub Import()

Dim wsmaster as workbook
Dim rd as range

Application.ScreenUpdating = False
Application.DisplayAlerts = False

    If wsmaster Is Nothing Then
        ThisWorkbook.Sheets.Add
        Set wsmaster = ActiveSheet
        Set rd = wsmaster.Range("A1")
        wsmaster.Name = "Data"
        filespec = Application.GetOpenFilename()
        Set wb = Workbooks.Open(Filename:=filespec)
        Sheets("Reviewed").Activate
        Cells.Copy rd
        wb.Close
    End If

Application.ScreenUpdating = True
Application.DisplayAlerts = True


End Sub

2 个答案:

答案 0 :(得分:0)

您不能只覆盖现有的工作表。您需要首先删除现有的“数据”表,然后添加新表,或者只是在现有表中写入新数据(可能首先清除所有其他数据)。

删除工作表的版本1可能如下所示:

Sub Import()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

    If wsmaster Is Nothing Then
        Worksheets("Data").Delete
        ThisWorkbook.Sheets.Add
        Set wsmaster = ActiveSheet
        Set rd = wsmaster.Range("A1")
        wsmaster.Name = "Data"
        filespec = Application.GetOpenFilename()
        Set wb = Workbooks.Open(Filename:=filespec)
        Sheets("Reviewed").Activate
        Cells.Copy rd
        wb.Close
    End If

Application.ScreenUpdating = True
Application.DisplayAlerts = True


End Sub

第二种选择是这样的:

Sub Import()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

    If wsmaster Is Nothing Then
        Set wsmaster = Worksheets("Data")
        Set rd = wsmaster.Range("A1")
        wsmaster.Cells.Clear
        filespec = Application.GetOpenFilename()
        Set wb = Workbooks.Open(Filename:=filespec)
        Sheets("Reviewed").Activate
        Cells.Copy rd
        wb.Close
    End If

Application.ScreenUpdating = True
Application.DisplayAlerts = True


End Sub

答案 1 :(得分:0)

rohrl77,谢谢你给我提供反馈。找到解决方案:

Sub import_click()

    Call deletedatasheet

    Call import

    MsgBox "Data blev importeret", vbInformation

End Sub

Private Sub import()

Dim wsMaster As Worksheet
Dim rd As Range

Application.ScreenUpdating = False
Application.DisplayAlerts = False

    If wsMaster Is Nothing Then
        ThisWorkbook.Sheets.Add
        Set wsMaster = ActiveSheet
        Set rd = wsMaster.Range("A1")
        wsMaster.Name = "Data"
        filespec = Application.GetOpenFilename()
        Set wb = Workbooks.Open(Filename:=filespec)
        Sheets("Reviewed").Activate
        Cells.Copy rd
        wb.Close
    End If

Application.ScreenUpdating = True
Application.DisplayAlerts = True


End Sub

Sub deletedatasheet()
    Dim ws As Worksheet

    Application.DisplayAlerts = False
    For Each ws In ThisWorkbook.Sheets
        If ws.Name = "Data" Then
            ws.Delete
        End If
    Next
    Application.DisplayAlerts = True
End Sub