我已经编写了VBA代码,用于打开目标工作簿,复制其中一个工作表,然后将其粘贴到当前工作簿中。
当我第二次或第三次运行它时...而不是覆盖当前工作表,而是创建一个全新的工作表。
例如:工作表称为“数据”,第一次是传输“数据”,第二次是“ data(2)”。
我还有另一个工作表,该工作表使用VLOOKUP函数查看此数据工作表的某些单元格,因此至关重要的是,它具有正确的名称“数据”。
我考虑过在运行宏之前删除当前(数据)文件,但是如果发生崩溃而丢失工作表怎么办?有更好的解决方案吗?
注意:我正在从主工作簿中运行宏,以从外部工作簿中复制工作表。
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
答案 0 :(得分:1)
用于检查工作表是否存在的功能(贷记@ScottCrainer):
Function SheetExists(ws As String)
SheetExists = Not IsError(Application.Evaluate(ws & "!A1"))
End Function
注意:
确实存在问题:如果工作表上的A1包含错误,则会返回假阴性。
答案 1 :(得分:0)
您在代码中使用了“ Activeworkbook”和“ Sheet(s)”,所以我一直在玩。
尽管您可以使用第三本工作簿来运行代码,但我猜测您是通过“ ActiveWorkbook ”中的模块来运行代码的。如果是这样,则使用“ ThisWorkbook ”代替总是引用包含代码(模块)的工作簿会更正确 ,以避免意外地在第三个工作簿上运行代码。
工作表是指工作表和图表表,我再次猜测此代码中不涉及任何图表表,因此使用“ 工作表”而不是“工作表”更为正确。
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
下次您要对工作表进行操作时,必须取消保护,否则代码将失败。 隐藏的工作表可以删除,没有问题。