【问题标题】:Search an Excel Column from Access VBA - Type Mismatch从 Access VBA 中搜索 Excel 列 - 类型不匹配
【发布时间】:2016-01-30 03:18:46
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    我不相信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:=... 参数。

    【讨论】:

    • 我认为我们必须使用第二个选项(.Cells(1)),bc ActiveCell 不是 Worksheet 的成员,而是 Application,我错了吗?
    • 有效!这两种方法都对我有用,但我会按照您的建议使用 xl.Cells(1)。我很感激帮助。干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多