将提示的Excel电子表格设置为新的工作簿对象

时间:2018-03-09 17:58:06

标签: excel vba excel-vba

我正在尝试分配一个新的Excel工作表,该工作表正在提示作为新的工作簿对象打开。我正在尝试以下代码,但它无法正常工作

Option Explicit

Sub MoveGeneratedReport()

   Dim newWbReport As Workbook
   Dim MonthlyComplianceReport As Workbook

   Set MonthlyComplianceReport = SelectWorkbook

End Sub

Private Function SelectWorkbook() As Workbook

   Dim strFileToOpen As String
   strFileToOpen = Application.GetOpenFilename(Title:="Select Compliancy Report for export", _
                   FileFilter:="Excel Files *.xls* (*.xls*),")

   If strFileToOpen <> False Then  '<---- Error Ocuring here
      Workbooks.Open Filename:=strFileToOpen
   End If

End Function

我收到了

  

“类型不匹配”

错误,但是如果我只运行函数SelectWorkbook(),它可以正常工作并打开文档。

我的最终目标是打开文档,然后将其分配给Workbook对象。有任何修复此错误的建议吗?

修改

我也应该在这里澄清我的问题...如何通过提示将这个新打开的工作簿分配给Workbook对象,以便我的其余代码可以使用它?

编辑2:

这似乎工作得很好

Option Explicit

Sub MoveGeneratedReport()

   Dim newWbReport As Workbook
   Dim MonthlyComplianceReport As Workbook

   Set MonthlyComplianceReport = SelectWorkbook


   Debug.Print MonthlyComplianceReport.Name

End Sub

Private Function SelectWorkbook() As Workbook

   Dim strFileToOpen As String
   strFileToOpen = Application.GetOpenFilename(Title:="Select Compliancy Report for export", _
                   FileFilter:="Excel Files *.xls* (*.xls*),")

   If strFileToOpen <> "" Then
      On Error GoTo ErrHandle
      Set SelectWorkbook = Workbooks.Open(Filename:=strFileToOpen)
   End If

   Exit Function
ErrHandle:
   If Err.Number <> 1004 Then
      MsgBox "Error " & Str(Err.Number) & Chr(13) & _
             "Error Line: " & Erl & Chr(13) & Chr(13) & _
             Err.Description
   End If

End Function

1 个答案:

答案 0 :(得分:2)

GetOpenFilename会返回String,因此它不会是真或假。改为测试空字符串:

If strFileToOpen <> "" Then

编辑:

要设置工作簿对象,请将其更改为:

Private Function SelectWorkbook() As Workbook
   Dim strFileToOpen As String
   strFileToOpen = Application.GetOpenFilename(Title:="Select Compliancy Report for export", _
                   FileFilter:="Excel Files *.xls* (*.xls*),")

   If strFileToOpen <> "" Then
      Set SelectWorkbook = Workbooks.Open(Filename:=strFileToOpen)
   End If

End Function