【问题标题】:invalid procedure call or argument excel - Error 5 in a for loop无效的过程调用或参数 excel - for 循环中的错误 5
【发布时间】:2021-01-05 22:37:55
【问题描述】:

我使用下面的代码 sn-p 从 xls 文件写入 txt。显然它适用于 excel 中的前 11 行,然后在此行抛出无效过程错误。有人可以在这里帮忙吗,不确定是什么阻止了循环继续进行,在评论这一行时循环按预期运行,这个函数导致了问题。

oFile.WriteLine 光标字符串

Dim FSO As Object

Set FSO = CreateObject("Scripting.FileSystemObject")
Dim oFile As Object
Set oFile = FSO.CreateTextFile(TXTfilepath)
'Set objfile = objFSO.OpenTextFile("C:\Test\PhoneList.csv", 1)
'Set oFile = FSO.OpenTextFile("C:\Users\klukiyan\Desktop\test.txt", 2)

'what to do
Acolumn = 1
currowstring = ""
LastRow = Cells(Rows.Count, "A").End(xlUp).Row

For Arow = 2 To LastRow
            For Acolumn = 1 To 84
            If Acolumn = Val(Right(Cells(1, Acolumn), 3)) + 3 Then
            currowstring = currowstring & Cells(Arow, Acolumn) & ","
            Acolumn = Acolumn + 1
            Else
            currowstring = currowstring & ","
            End If
            Next Acolumn
            oFile.WriteLine currowstring
            currowstring = ""
            Acolumn = 1
Next Arow

【问题讨论】:

  • 准确显示错误所在的行,人们计算代码行的方式不同。然后查看Cells() 的值,其中出现了错误。例如,输入MsgBox(Cells(1,Acolumn).Address) 并手动查看。是错误还是意外字符串?
  • 感谢@Vityata,我确实检查了,问题从第 11 行数据开始。虽然我有 60 多行数据,但只有前 11 行被写入 txt 文件,当循环开始到第 12 行时,这行代码 - oFile.WriteLine currowstring 抛出错误 5,如果我评论这一行循环运行,但没有写入 txt 文件的行。
  • Debug.Print currowstring,看看应该写什么值。

标签: excel vba object


【解决方案1】:

从包含一些虚拟数据的空 Excel 开始,尝试尽可能少地编写,使用一些幻数进行硬编码,然后逐步从小的硬编码代码到您的代码。在其中一个步骤中,将显示错误原因。这应该是一个开始:

Option Explicit
Sub TestMe()

    Dim FSO As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Dim oFile As Object
    Set oFile = FSO.CreateTextFile("C:\Users\yourname\export.csv")
    
    Dim acolumn As Long
    Dim arow As Long
    
    Dim currowstring As String: currowstring = ""
    
    For arow = 2 To 50
        For acolumn = 1 To 84
            currowstring = currowstring & Worksheets("NAME_OF_WORKSHEET").Cells(arow, acolumn) & ","
            acolumn = acolumn + 1
        Next acolumn
        
        oFile.WriteLine currowstring
        currowstring = ""
    
    Next arow

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    相关资源
    最近更新 更多