excel - 从 Access VBA 中搜索 Excel 列 - 类型不匹配

标签 excel ms-access vba ms-access-2007

我的问题发生在以下行(错误是类型不匹配):

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

背景:我正在构建一个数据库,它加载一个文本文件,将其拆分为多个不同的部分,组合一些部分以创建新表,然后将新表导出到 Excel 并进行一些格式化。

我使用“For Each”循环来浏览我的 Access 表。当某些表被识别时,一些其他代码运行创建新表(代码未显示)。创建新表后,将导出到 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

最佳答案

我不相信 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 Excel.Application 的一部分引用父工作表。

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

关于excel - 从 Access VBA 中搜索 Excel 列 - 类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33423435/

相关文章:

vba - 如何获取范围内的范围值

vba - 自动打开一个excel文件到所有工作表中的单元格A1(使用VBA)

ms-access - 对于某些操作值, Access SysCmd 功能无法按预期工作

mysql - MS Access VBA 从表单写入表

java - VBA获取带有空格字符(例如换行符和回车符)的字符串长度

vba - Excel 相机工具 - 将图像大小调整为 100% 比例

excel - 同价求和数量,excel

java - 从 Microsoft Access 调用 Java 程序

excel - 从 VBA 中的多个按钮调用相同的 SUB

vba - 为什么我不能传递数组(数组内)作为参数?