使用Word VBA来自动化Excel,我得到运行时错误“13”:使用.Find函数时types不匹配

我试图从一个Excel表格获取数据到一个Word文档。 我尝试使用“查找”function,但我不断收到相同的错误“types不匹配”在这一行:

Set FoundRange = .Cells.Find(260707) 

这是我正在运行的子程序。

  Sub GetID() Dim oXL As Object Dim oWB As Object Dim oSheet As Object Dim WorkbookToWorkOn As String Dim FoundRange As Range Dim dummyvar As String 'Start a new instance of Excel Set oXL = CreateObject("Excel.Application") 'Line to make Excel Visible or not oXL.Visible = False 'Open the workbook 'Set the file path to access the 'Certified Personnel' table WorkbookToWorkOn = "\\DataSource\CertifiedPersonnel.xlsx" Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn, ReadOnly:=True, IgnoreReadOnlyRecommended:=True) Set oSheet = oXL.ActiveWorkbook.Sheets("tblCertifiedPersonnel") 'End of Excel Automation. Everything from this point on can reference Excel. With oSheet dummyvar = .Cells(1, 2).Text .Cells(1, 2).Select 'Set the range of the cell containing the ID number 'If the ID was found Set FoundRange = .Cells.Find(260707) If Not FoundRange Is Nothing Then 'Set the NTlogin equal to the value of column 1, and row corresponding to the FoundRange row NTlogin = .Cells(FoundRange.Rows, 1).Text Role = .Cells(FoundRange.Rows, 4).Text End If End With 'End Excel reference oXL.ActiveWorkbook.Close SaveChanges:=False oXL.Application.Quit Set oXL = Nothing Set oWB = Nothing Set oSheet = Nothing End Sub 

我知道它正在访问正确的工作簿,因为虚拟variables(dummyvar)正在返回我期望的值。 我已经尝试了几个与“查找”function相关的东西,但是我一直没有能够得到它的工作。 有任何想法吗? 非常感激。

您正在使用后期绑定,并将FoundRange声明为Range 。 由于这是在Word文档中,所以在这里隐式声明它为一个Word.Range

 Dim FoundRange As Range 

.Find返回一个Excel.Range 。 将其更改为:

 Dim FoundRange As Object 

假设ID值作为文本存储在工作表中,或者使用单元格types的文本,或者在数字前加撇号/单引号,则可能需要将ID格式化为string。 随着进一步的假设,最终你可能想通过parameter passing给过程,请尝试一下:

Set FoundRange = .Cells.Find(CStr(260707))

如果需要的话,这也可以让你用一个variablesreplace常数。