3

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

'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

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

4

2 回答 2

2

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

没有 Excel 参考:

Dim interestingFiles As Variant

并使用 Excel 参考:

Dim interestingFiles As Excel.Range
于 2013-05-05T16:04:37.013 回答
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
于 2013-05-05T13:00:36.970 回答