我很抱歉,因为我是vba代码的新手。我遇到以下代码的问题。我正在尝试打开一个文件,然后将该文件中的所有工作表复制到当前工作簿。它当前返回运行时错误424
Private Sub testGetFile()
Dim wb1, wb2 As Workbook
Dim sh As Worksheet
Set wb1 = ThisWorkbook
Set wb2 = Application.GetOpenFilename
For Each sh In wb2
sh.Copy After:=wb1.Sheets(wb1.Sheets.Count)
Next
End Sub
答案 0 :(得分:0)
您没有正确使用GetOpenFilename
。由于它不是Workbook
对象,因此无法将其直接设置为工作簿。
我清理过的代码还有其他几个地方。
Option Explicit
Private Sub testGetFile()
Dim wb1 As Workbook
Set wb1 = ThisWorkbook
Dim fileToOpen As Variant
fileToOpen = Application.GetOpenFilename
If fileToOpen = False Then
Exit Sub
Else
Dim wb2 As Workbook
Set wb2 = Workbooks.Open(fileToOpen)
End If
Dim sh As Worksheet
For Each sh In wb2.Worksheets
sh.Copy After:=wb1.Sheets(wb1.Sheets.Count)
Next
End Sub
答案 1 :(得分:0)
wb2
是一本工作簿,GetOpenFilename
返回String
。例如,您必须获取返回的String并使用它将其设置为wb2
:
Dim fileName As String
fileName = Application.GetOpenFilename()
Workbooks.Open fileName