我的问题发生在以下行(错误是类型不匹配):
RowNo = xlSheet1.Cells.Find(What:="SummaryType", After:=ActiveCell, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Row
背景:我正在构建一个数据库,它加载一个文本文件,将它拆分成许多不同的部分,组合一些部分来制作新表,然后将新表导出为excel并进行一些格式化。
我使用'For Each'循环遍历我的访问表。当识别出某些表时,会运行一些其他代码来创建新表(代码未显示)。创建新表后,将导出到excel并进行格式化。这是发生错误的地方。第一个循环工作正常,在第二个循环中,代码在尝试查找A列中包含“SummaryType”的行时出错。错误是运行时错误13 - 类型不匹配。
代码:
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
答案 0 :(得分:3)
我不相信正确识别ActiveCell property。这不属于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
部分{/ 1}}。
或者,任何单元格都可以(例如Excel.Application
),或者您可以简单地省略.Cells(1)
参数。