2013-05-05 12 views
2
設置Excel範圍時

我有我的分部分試圖指定範圍下面的代碼:VBA類型不匹配的錯誤在Word

'Set xlApp = CreateObject("Excel.Application") 

Dim xlApp As Object 
Set xlApp = GetObject(, "Excel.Application") 
xlApp.Visible = False 
xlApp.ScreenUpdating = False 

Dim CRsFile As String 
Dim CRsMaxRow As Integer 

' get the CR list 
CRsFile = "CRs.xls" 
Set CRsWB = xlApp.Workbooks.Open("C:\Docs\" + CRsFile) 
With CRsWB.Worksheets("Sheet1") 
    .Activate 
    CRsMaxRow = .Range("A1").CurrentRegion.Rows.Count 

    Set CRs = .Range("A2:M" & CRsMaxRow) 

End With 

Dim interestingFiles As Range 

' get the files names that we consider interesting to track 
Set FilesWB = xlApp.Workbooks.Open("files.xlsx") 
With FilesWB.Worksheets("files") 
    .Activate 
    Set interestingFiles = .Range("A2:E5") 
End With 

你有爲什麼我得到一個運行時類型不匹配的任何想法錯誤?

回答

0

請在下面的代碼中設置xlApp對象。 另外,您在打開工作簿時也提供完整的路徑。

Sub test() 
     Dim interestingFiles As Range 
     Dim xlApp As Object 

     Set xlApp = GetObject(, "Excel.Application") 
     ' get the files names 

     Dim path As String 
     path = "C:\Users\Santosh\Desktop\file1.xlsx" 

     Set FilesWB = xlApp.Workbooks.Open(path) 
     With FilesWB.Worksheets(1) 
      .Activate 
      Set interestingFiles = .Range("A2:E5") 
     End With 

    End Sub 
+0

沒有設置'xlApp'我期望一個'424對象required'錯誤,或者如果該文件沒有按」 t存在,那麼'Set FilesWB = ...'會出現錯誤,但是OP表示設置範圍的「不匹配」錯誤。我沒有看到那個'With'塊裏面有什麼不正確的東西。 – 2013-05-05 13:04:17

+0

@DavidZemens你認爲它的'xlApp.Workbooks.Open(「files.xlsx」)是個問題嗎? – Santosh 2013-05-05 13:06:28

+0

在m代碼我把完整的路徑 - 我不覺得舒服在網上... ... – banjo 2013-05-05 13:11:25

2

如果你從Word運行代碼,那麼問題出現在'interestingFiles'變量的聲明中。 範圍也存在Word中所以使用Variant或添加引用到Excel,然後使用Excel.Range。

沒有Excel引用:

Dim interestingFiles As Variant 

並與Excel引用:

Dim interestingFiles As Excel.Range 
+0

唉這可能會成爲問題的根源。 OP沒有說什麼應用程序正在運行這個子程序,但這是有道理的。 – 2013-05-05 16:12:41

+0

確認這將解決Word中的問題:)幹得好! – 2013-05-05 16:14:46