我正在为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
但我不想使用硬编码字符串来获取工作表名称设置ws1 = Wb1.Worksheets(“任务”)。而是想使用函数参数。
以下代码不起作用:
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
答案 0 :(得分: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中的保留字。您仍然可以将它用作变量/参数名称,但您可能不应该这样做。