将 Trim 应用于单元格...值生成应用程序定义的错误

Applying Trim to Cells...Value generates application defined error

下面的代码应该将文本文件导入到 Excel。

我想 trim 一些列,因为一些字段有空格而不是空值,这在导入访问时给我带来了问题,因为这些字段的数据类型是日期。

我 运行 在代码的 Trim 部分出现应用程序定义的错误。

Dim xl As excel.Application
Dim wbk As excel.Workbook
Dim wst As excel.Worksheet
Dim DFPath
'DFPath reference folder, not the file
DFPath = Forms!DailyFileMacro!OutFilePath
Dim DFname
DFname = Forms!DailyFileMacro!OutFileName

Set xl = CreateObject("Excel.Application")
With xl
    .Visible = True
    Set wbk = .Workbooks.Add
    Set wst = wbk.Worksheets(1)
    With wst.QueryTables.Add(Connection:="TEXT;" & Forms!DailyFileMacro!InFilePath & Forms!DailyFileMacro!InFileName, Destination:=Range("$A"))
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 2, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 3, 3, _
        1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False

    Dim rowcount As Long
    rowcount = Range("A1").SpecialCells(xlCellTypeLastCell).Row
    For i = 2 To rowcount
        If Cells(i, 19).Value Like "Adjustment*" Then
            Cells.Offset(0, 1).Value = Trim(Cells.Offset(0, 1).Value)
            Cells.Offset(0, 2).Value = Trim(Cells.Offset(0, 2).Value)
        End If
    Next i
End With

End With
wbk.SaveAs Filename:=(DFPath & DFname), FileFormat:=56
wbk.Close SaveChanges:=False
xl.Quit

基于 If Cells(i, 19).Value,我想你的意思是 Trim 两行是:

Cells(i, 20).Value = Trim(Cells(i, 20).Value)
Cells(i, 21).Value = Trim(Cells(i, 21).Value)

Cells 调用按原样(没有 row/column 引用或父 Range 引用)引用 整个 Worksheet,因此 Offset 不可能按 1 或 2 列进行调整,并且总是会引发 运行 时间错误。