简体   繁体   English

在工作簿之间复制工作表并覆盖当前工作表

[英]Copy worksheet between workbooks and overwrite the current worksheet

I have written VBA code that opens up a destination workbook, copies one of the worksheets, and pastes it into the current workbook. 我编写了VBA代码,用于打开目标工作簿,复制其中一个工作表,然后将其粘贴到当前工作簿中。

When I run it a second or third time etc... instead of overwriting the current worksheet, it creates a completely new one. 当我第二次或第三次运行它时...而不是覆盖当前工作表,而是创建一个全新的工作表。

Ex: Worksheet is called "data", first time it transfers "data", second time "data(2)". 例如:工作表称为“数据”,第一次是传输“数据”,第二次是“ data(2)”。

I have another worksheet that uses VLOOKUP function to look at some cells of this data worksheet, so it is crucial that it has correct name "data". 我还有另一个工作表,该工作表使用VLOOKUP函数查看此数据工作表的某些单元格,因此具有正确的名称“数据”至关重要。

I thought about deleting the current (data) file before running the macro, but what if something crashes and I lose my worksheet? 我曾考虑过在运行宏之前删除当前(数据)文件,但是如果发生崩溃而丢失工作表怎么办? Is there a better solution? 有更好的解决方案吗?

NOTE: I am running the macro from the main workbook to get the sheet to be copied from the external workbook. 注意:我正在从主工作簿运行宏,以获取要从外部工作簿复制工作表。

Sub UpdateT()

    Dim wb As Workbook
    Dim aw As Workbook

    'Open 2nd Workbook
    Set aw = Application.ActiveWorkbook
    Set wb = Workbooks.Open(Filename:="C:\Users\yilmadu00\Desktop\T.xlsx")

    'Copy To Different Workbook
    wb.Sheets("data").Copy After:=aw.Sheets("Data1")

    'Close 2nd Workbook
    aw.Save
    wb.Close

    aw.Sheets("data").Visible = False
    ActiveWorkbook.Protect ("Password")

End Sub

Function to check whether worksheet exists (credits to @ScottCrainer): 检查工作表是否存在的函数(贷记@ScottCrainer):

Function SheetExists(ws As String)
    SheetExists = Not IsError(Application.Evaluate(ws & "!A1"))
End Function
NOTE: 注意:

It does have the issue: if A1 on the sheet contains an error it will return a false negative. 它的确存在问题:如果工作表上的A1包含错误,它将返回假阴性。

ActiveWorkbook vs ThisWorkbook, Sheets vs Worksheets ActiveWorkbook与ThisWorkbook,工作表与工作表

You have used 'Activeworkbook' and 'Sheet(s)' in the code so I played along. 您在代码中使用了“ Activeworkbook”和“ Sheet(s)”,所以我一直在玩。

But

Although you can have a third workbook to run the code from, I'm guessing you are running the code from a module in the ' ActiveWorkbook '. 尽管您可以拥有第三本工作簿来运行代码,但我猜您是从“ ActiveWorkbook ”中的模块运行代码的。 If this is true, it would be more correct to use ' ThisWorkbook ' instead which always refers to the workbook that contains the code (module) , to avoid accidentally running the code on a third workbook. 如果这是真的,那么使用“ ThisWorkbook ”代替它总是引用包含代码(模块)的工作簿会更正确 ,以避免在第三个工作簿上意外地运行代码。

Sheet(s) refers to Worksheet(s) and Chartsheet(s) , again I'm guessing there are no chartsheets involved in this code, therefore it would be more correct to use ' Worksheet(s) ' instead of 'Sheet(s)'. 工作表是指工作表和统计表 ,再次,我猜想此代码中不涉及工作表 ,因此使用“ 工作表 ”代替“ 工作表 ”会更正确)”。

Sub UpdateT()

  Const cStrPath As String = "C:\Users\yilmadu00\Desktop\T.xlsx"
  Const cStrAfter As String = "Data1"
  Const cStrName As String = "data"
  Const cStrOld As String = "data_old"

  Dim aw As Workbook '1st workbook, 'ActiveWorkbook'
  Dim wb As Workbook '2nd workbook
  Dim oWs As Sheet 'Each sheet in workbook 'aw'
  Dim blnFound As Boolean 'True if sheet(cStrName) was found

  Set aw = ActiveWorkbook 'Create a reference to the ActiveWorkbook
  Set wb = Workbooks.Open(Filename:=cStrPath) 'Open 2nd Workbook

  With aw
  '  .UnProtect ("Password")
    'Check each sheet in workbook 'aw'.
    For Each oWs In aw.Sheets
      With oWs
        'Check if there already is a sheet with the name 'cStrName'.
        If .Name = cStrName Then
          .Name = cStrOld 'Rename the sheet.
          blnFound = True 'Sheet(cStrName) was found.
          Exit For 'Immediately stop checking, there can only be one.
        End If
      End With
    Next
  End With

  With wb
    'Copy sheet from 2nd workbook ('wb') to workbook 'wa'.
    .Sheets(cStrName).Copy After:=aw.Sheets(cStrAfter)
    .Close 'Close 2nd workbook ('wb').
  End With

  With aw
    With Application
      If blnFound = True Then 'Sheet(cStrName) was found.
        .DisplayAlerts = False 'Disable showing delete message.
        aw.Sheets(cStrOld).Delete 'Delete old version of sheet.
        .DisplayAlerts = True
      End If
    End With
    .Sheets(cStrName).Visible = False 'Hide sheet named 'cStrName'
    .Protect ("Password")
    .Save 'Save workbook 'aw'.
  End With

End Sub

The next time you want to do something with the sheet you have to unprotect it or the code will fail. 下次您要对工作表执行某些操作时,必须取消保护它,否则代码将失败。 Hidden sheets can be deleted with no problems. 隐藏的工作表可以毫无问题地删除

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM