我正在编写vba代码来远程控制网络上的设备。基本上设备会输出一个txt文件,我需要我的代码来进行后期处理。这个想法不是必须使用deliminator手动打开excel中的txt文件。这就是问题所在。
打开文件的代码段如下:
Workbooks.OpenText fileName:= _
path, _
origin:=437, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, Semicolon:=False, _
Comma:=True, Space:=False, Other:=False, FieldInfo:=Array(1, 1), _
TrailingMinusNumbers:=True
代码在此处停止,并显示一个消息框" Excel无法访问' filename'。该文件可能是只读的或加密的。"
我做了一些消除:
我现在唯一能想到的是路径是基于网络的(例如" \ 192.168.202.1 \ user(d)\ User Files \ filename.txt")。顺便说一下网络工作正常。我尝试在Windows资源管理器中输入路径,没有任何问题。
请指教。谢谢!
答案 0 :(得分:0)
如果我发布的VBScript有效,我看不出以下代码在VBA中不起作用的任何原因(我写这篇文章来处理文本文件,如你在评论中描述的那样)。
如果你愿意的话,试一试让我知道它是怎么回事。将实际的文本文件目录替换为" C:\ test.txt"
Sub Test()
Dim File As TextStream
Set fso = CreateObject("SCripting.FileSystemObject")
Set File = fso.OPenTextFile("C:\test.txt")
'Example Reading Values to Collection Object
Dim Text As Collection
Set Text = New Collection
'Skip first 2 lines
For i = 1 To 2
File.SkipLine
Next
'Find first line that meets a condition
'This example uses the condition that
'the the current line of text starts with a number
Do
TempString = File.ReadLine
Loop Until IsNumeric(Left(TempString, 1))
'Current structure includes initial line from condition to be read
Text.Add Split(TempString, ",")
'Continue reading to end of file
Do Until File.AtEndOfStream
'Added protection against empty lines producing subscript
'out of range error if array expected
TempString = File.ReadLine
If TempString <> "" Then
Text.Add Split(TempString, ",")
End If
Loop
'Example Converting Collection to Array
Dim A1() As Variant 'First Column of Data
Dim A2() As Variant 'Second Column of Data
ReDim A1(Text.Count, 1 To 2)
ReDim A2(Text.Count, 1 To 2)
For i = 1 To Text.Count
A1(i, 1) = Text(i)(0)
A2(i, 1) = Text(i)(1)
Next
'Example Writing Array to Range
Range("A1:A" & Text.Count) = A1
Range("C1:C" & Text.Count) = A2
End Sub