【发布时间】:2021-01-27 15:41:37
【问题描述】:
我在过去几次用 excel 和宏编写了 txt 文件。我没有达到10000行或更多。永远不要说永远...
我的 .csv 文件有超过 87000 行,如该示例 "15k50,CityABC,56ab,CountryofCity,ID,Street"。我使用 Split() 函数来分隔值。宏格式化并将值作为单行写入 txt 文件。
大约 9800 行 txt 文件关闭...但是为什么呢?我尝试使用 Slepp() 来确保打印算法没有过载或其他问题。
计数器 10000 在那里是因为我想让你更容易理解。如果超过 10000,则问题已“解决”。
信息txt-文件格式:
- ASCII
- Unix (LF)
捷径,经过几次cmets
- 用Minimal, Reproducible Example 过度使用代码(删除睡眠,简化变量名,尝试从头开始编写代码)
- 将
SplitString()更改为Split(),因为调用函数很愚蠢... - 在将第 9000 行打印到 txt 文件后,在代码行
fso.WriteLine ("# " & strArr(0) & " # " & strArr(1) & ...处弹出以下错误“运行时错误 5:无效的过程调用或参数”
Option Explicit
#If VBA7 Then
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr) 'For 64 Bit Systems
#Else
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 'For 32 Bit Systems
#End If
Sub formattedToTxt()
Dim strArr() As String
Dim strB As String
Dim intC As Integer
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
strB = filePathExport & "\" & filenameExport & fileFormatExport
Set fso = fso.CreateTextFile(strB, True)
Do While counter <= 10000
strArr = Split(ActiveCell.Value, ",")
intC = CalcWhitespace(strArr(5), 40)
fso.WriteLine ("# " & strArr(0) & " # " & strArr(1) & " # " & strArr(2) & " # " & strArr(3) & " # " & strArr(4) & " # " & strArr(5) & Space(intC) & "#")
ActiveCell.Offset(1, 0).Select
If ((counter Mod 1000) = 0) Then
Debug.Print ("Entry " & counter & " written")
End If
counter = counter + 1
Loop
End Sub
Function CalcWhitespace(rawStr As String, maxLen As Integer) As Integer
CalcWhitespace = maxLen - Len(rawStr)
End Function
有什么想法吗?
【问题讨论】:
-
你得到了哪个错误,代码在哪里?你的代码应该做什么,而不是做什么?实际上它不能像没有子或函数一样运行(参见minimal reproducible example)。请注意,如果您将
Sleep 1000放入一个包含 10000 的循环中,则总共需要等待 2.77 小时! • 为什么不直接填写工作表并使用 Excel 中的安全文本功能? • 你的问题很不清楚。 -
“txt 文件已关闭” 是什么意思?程序继续运行但没有写入数据?程序停止了吗?任何运行时错误?忘记
sleep,这不会导致任何地方。你为什么要与Activecell和Select合作? -
阅读How to avoid using Select in Excel VBA可能会让您受益。
-
@Pᴇʜ Sleep 是一个函数,单位是毫秒,1000ms = 1s 我不能将该功能作为文本安全,因为打印到 txt 文件的输出格式不同。我尝试使用minimal reproducible example,感谢tipp
-
@EngineerTrooper 您在哪一行代码中得到错误?