从Access VBAsearchExcel列 – types不匹配

我的问题发生在下面一行(错误是types不匹配):

RowNo = xlSheet1.Cells.Find(What:="SummaryType", After:=ActiveCell, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Row 

背景:我正在构build一个数据库,它载入一个文本文件,将其分割成多个不同的部分,合并一些部分以创build新表格,然后将新表格导出为ex​​cel并进行一些格式化。

我使用“For Each”循环来查看我的访问表。 当某些表被识别时,一些其他代码运行创build新的表(代码未显示)。 一旦创build了一个新表,就会被导出为ex​​cel并进行格式化。 这是发生错误的地方。 第一个循环工作正常,在第二个循环中,当试图在列A中查找包含“SummaryType”的行时,代码出错。错误是运行时错误13 – types不匹配。

码:

 Dim outputFileName As String Dim xl As Excel.Application Dim xlBook As Excel.Workbook Dim xlSheet1 As Excel.Worksheet Dim RptMnth As String Dim RptYear As Long Dim RptName As String outputFileName = "C:\Users\UserID\Desktop\Reports\" & RptName & "_" & RptMnth & "_" & RptYear & ".xls" DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "tbl_Report", outputFileName, True Set xl = New Excel.Application Set xlBook = xl.Workbooks.Open(outputFileName) xl.Visible = True Set xlSheet1 = xlBook.Worksheets(1) With xlSheet1 .Columns("A").Delete Shift:=xlToLeft .Rows(1).Delete Shift:=xlUp .Range("A1:J1").Interior.Color = RGB(191, 191, 191) .Range("A1:J1").Borders.Weight = xlThin .Range("A1:J100").Font.Name = "Calibri (Body)" .Range("A1:J100").Font.Size = 11 .Range("A1:J1").HorizontalAlignment = xlCenter RowNo = xlSheet1.Cells.Find(What:="SummaryType", After:=ActiveCell, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Row .Range("A" & RowNo & ":F" & RowNo).Interior.Color = RGB(191, 191, 191) .Range("A" & RowNo & ":F" & RowNo).Borders.Weight = xlThin .Range("A" & RowNo & ":F" & RowNo).HorizontalAlignment = xlCenter .Range("A1:J100").Cells.Columns.AutoFit End With xl.DisplayAlerts = False xl.ActiveWorkbook.Save xl.ActiveWorkbook.Close xl.DisplayAlerts = True Set xlSheet1 = Nothing Set xlBook = Nothing Set xl = Nothing 

我不相信ActiveCell属性被正确识别。 这不在Excel VBA中,这些属性是自动的。

 RowNo = .Cells.Find(What:="SummaryType", After:=xl.ActiveCell, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Row 

取消多余的xlSheet1并使xl.ActiveCell引用父工作表的Excel.Application一部分。

或者,任何单元格都可以(例如.Cells(1) ),或者你可以简单地省略After:=...参数。