【问题标题】:vba excel - Run-time error '438': object doesn't support this property or method - Opentextfilevba excel - 运行时错误'438':对象不支持此属性或方法 - Opentextfile
【发布时间】:2018-06-08 11:31:12
【问题描述】:

我允许用户选择多个文件并找到其中行数最多的文件。当我运行下面的代码时,我在 Opentextfile 的行上收到“运行时错误'438'。-> txsInput = objFSO.OpenTextFile(FileName, ForReading)

Dim objFSO, txsInput, strTemp, arrLines
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")

Application.ScreenUpdating = False

'set and determine file picker behaviour
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = True

'Launch file picker, exit if no files selected. Hold Ctrl to select multiple files.
If Not fd.Show = -1 Then Exit Sub


'find longest file
For i = 1 To fd.SelectedItems.Count
    FileName = fd.SelectedItems(i)
    txsInput = objFSO.OpenTextFile(FileName, ForReading)

    'Skip lines one by one
    Do While txsInput.AtEndOfStream <> True
        txsInput.SkipLine ' or strTemp = txsInput.ReadLine
    Loop

    If longestFileLength < txsInput.Line - 1 Then
        longestFileLength = txsInput.Line - 1
        longestFileIndex = i
    End If

    'cleanup
    Set objFSO = Nothing
Next i
Cells(headerOffset, 20) = "Length" & longestFileLength
Cells(headerOffset, 21) = "index" & longestFileIndex

【问题讨论】:

  • Set objFSO = Nothing 发生在 inside 循环中,因此在第二次迭代中,它的Nothing 没有OpenTextFile(),你就会得到错误。
  • @AlexK。 - 我猜 OP 在第一次迭代时得到错误...
  • 没错,Nothing 问题将是错误 91

标签: vba excel


【解决方案1】:

快速修复(只是为了避免错误):

Dim objFSO, txsInput As Object, strTemp, arrLines

Set txsInput = objFSO.OpenTextFile(Filename, ForReading)

正常修复 - 正确声明变量,在顶部使用Option Explicit,然后声明以下变量:

  • fd
  • 文件名
  • 最长文件长度
  • 最长文件索引
  • headerOffset

如果你幸运的话,你的下一个错误会在这里:

Cells(headerOffset, 20) = "Length" & longestFileLength

因为headerOffset 的值是0。如果你在行前写headerOffset = 1,你会避免它。

【讨论】:

    猜你喜欢
    • 2018-04-30
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多