在Word中设置Excel范围时,VBA类型不匹配错误

时间:2013-05-05 12:51:39

标签: vba excel-vba word-vba excel

我有以下代码作为我的sub尝试分配范围的一部分:

'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

您是否知道我为什么会遇到运行时类型不匹配错误?

2 个答案:

答案 0 :(得分:2)

如果从Word运行代码,则问题出在'interestingFiles'变量的声明中。 Word中也存在范围,因此请使用Variant或添加对Excel的引用,然后使用Excel.Range。

没有Excel参考:

Dim interestingFiles As Variant

使用Excel参考:

Dim interestingFiles As Excel.Range

答案 1 :(得分: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