1

我正在为 excel 创建一个宏,用于将一个 excel 表复制到另一个 excel 表。

这是有效的:

Function CopyFile()

   Dim Wb1 As Workbook
   Dim Wb2 As Workbook
   Dim ws1 As Worksheet
   Dim ws2 As Worksheet

   Set Wb1 = ActiveWorkbook   
   Set ws1 = Wb1.Worksheets("Task")
   Set Wb2 = Workbooks.Open("D:\Outlook\dest.xlsx")

   ws1.Copy Wb2.Worksheets(1)

   Wb2.Save
   Wb2.Close
   Wb1.Activate   

End Function

但我不想使用硬编码字符串来获取工作表名称 Set ws1 = Wb1.Worksheets("Task")。而是想使用函数参数。

以下代码不起作用:

Function CopyFile(name As String)

   Dim Wb1 As Workbook
   Dim Wb2 As Workbook
   Dim ws1 As Worksheet
   Dim ws2 As Worksheet

   Set Wb1 = ActiveWorkbook

   Set ws1 = Wb1.Worksheets(name)
   Set Wb2 = Workbooks.Open("D:\Outlook\dest.xlsx")
   ws1.Copy Wb2.Worksheets(1)

   Wb2.Save
   Wb2.Close
   Wb1.Activate

End Function
4

1 回答 1

2

这个对我有用。如果你传递一个不存在的名字,你会得到一个错误。也许

Function CopyFile(sSheetName As String)

    Dim wbSource As Workbook
    Dim wbDest As Workbook
    Dim wsSource As Worksheet
    Dim wsDest As Worksheet

    Set wbSource = ActiveWorkbook

    On Error Resume Next
        Set wsSource = wbSource.Worksheets(sSheetName)
    On Error GoTo 0

    If Not wsSource Is Nothing Then
        Set wbDest = Workbooks.Open("D:\Outlook\dest.xlsx")
        wsSource.Copy wbDest.Worksheets(1)

        wbDest.Save
        wbDest.Close
        wbSource.Activate
    End If

End Function

作品“名称”是 VBA 中的保留字。您仍然可以将其用作变量/参数名称,但您可能不应该这样做。

于 2012-05-09T13:28:26.443 回答