首页 文章

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

提问于
浏览
2

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

'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

    如果您从Word运行代码,则问题出在'interestingFiles'变量的声明中 . Range exist in Word as well 所以使用Variant或添加对Excel的引用,然后使用Excel.Range .

    没有Excel参考:

    Dim interestingFiles As Variant
    

    并使用Excel参考:

    Dim interestingFiles As Excel.Range
    
  • 2

    请设置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
    

相关问题