VBA相当新鲜。我试图从另一个excel文件中拉出一张表并将其放在活动工作簿中。我已经这样做了,但是我想设置它,以便每次运行代码时它都会用新工作表替换旧工作表,而不是在程序继续使用时添加无限量的工作表。有什么帮助吗?
以下是我目前使用的代码:
Private Sub CommandButton2_Click()
Dim sh As Worksheet, wb As Workbook
Set wb = Workbooks("QI VBA.xlsm")
For Each sh In Workbooks("Example.xlsx").Worksheets
If sh.Name = "Sheet1" Then
sh.Copy After:=wb.Sheets(wb.Sheets.Count)
End If
Next sh
End Sub
答案 0 :(得分:1)
我拿出了你的循环,因为它写得似乎是多余的。
Private Sub CommandButton2_Click()
Dim wb as Workbook
Set wb = Workbooks("QI VBA.xlsm")
If WorksheetExists(wb, "Sheet1") Then
Application.DisplayAlerts = False
wb.Worksheets("Sheet1").Delete
Application.DisplayAlerts = True
End If
Workbooks("Example.xlsx").Worksheets("Sheet1").Copy After:= wb.Sheets (wb.Sheets.Count)
End Sub
Function WorksheetExists(wb As Workbook, sWSName As String) As Boolean
'=================================================================================================================================
'== Name: WorksheetExists
'== Purpose: To check if a worksheet exists in a given workbook
'== Notes: On Error Resume Next only used to make this a quicker process ...
' try to name of sheet passed, if it fails, sheet doesn't exist
'=================================================================================================================================
On Error Resume Next
Dim ws As Worksheet
Set ws = wb.Worksheets(sWSName)
WorksheetExists = Err.Number = 0
On Error GoTo 0
End Function