【问题标题】:Replace Excel Worksheet with Sheet from another file with VBA用 VBA 将另一个文件中的工作表替换为 Excel 工作表
【发布时间】:2017-07-22 00:46:52
【问题描述】:

对 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

【问题讨论】:

    标签: vba excel


    【解决方案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
    

    【讨论】:

    • 我收到一条错误消息,指出“编译错误:ByRef 参数类型不匹配”。对出了什么问题有什么建议吗?
    • @a.powell - 我忘了声明工作簿对象。立即尝试。
    • @a.powell - 立即尝试。 (不知何故没有在After:之后添加=
    猜你喜欢
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多