0

处理宏以从另一个工作簿复制一些数据并将其粘贴到具有宏的工作簿中的工作表上。我正在使用从另一个线程改编而来的这个函数来获取外部工作​​簿的文件路径:

    Public Function RetrieveFileName() As String

    'Show the open dialog and pass the selected file name to the String variable "sFileName"
    RetrieveFileName = Application.GetOpenFilename

    'They have cancelled.
    If RetrieveFileName = "False" Then
        Exit Function
    End If

End Function

它可以工作,我可以打开工作簿,但是当我尝试存储外部工作簿中的范围(下面代码段中的最后一行)时,vba 抛出运行时错误“13”:类型不匹配。

Sub CreateSystemExtracts()
Dim thisRow As Long, wbkCheck As Long
Dim countryFilter As String, systemFilter As String
Dim sourceBook As Workbook
Dim sourceHeaders As Range

'Ask user where source data sits
Set sourceBook = Workbooks.Open(RetrieveFileName())

'Make sure they provided a source
If sourceBook Is Nothing Then
    MsgBox "You must select a source file to continue, macro halted."
    Exit Sub
End If

'Check if number of rows in the selected file matches what we expect
sourceHeaders = Workbooks(sourceBook).Worksheets(Sheet1).Range("A2:X2")

你能告诉我哪里出错了吗?我认为这与我在最后一行声明范围的方式有关,但我尝试了很多不同的方法,都给出了运行时错误 13。

提前致谢!

4

1 回答 1

0

分配对象变量时,您需要使用Set

'Check if number of rows in the selected file matches what we expect 
Set sourceHeaders = Workbooks(sourceBook).Worksheets("Sheet1").Range("A2:X2")
于 2012-07-06T22:31:45.247 回答