我有一个输入文件,我正在努力逐行阅读,该文件可以找到here,也显示如下:
我想将第一个值添加为关键值,将第三个值添加为dictonary
中的项目然后我可以这样做:a = myDictonary(“CREATED_BY”),然后这将返回“Eigil ...”(顺序和行数我不时变化..)
但不知怎的,我无法让分裂发挥作用:
Dim hf As Integer: hf = FreeFile
Dim lines() As String, i As Long
Open FileName For Input As #hf
Line Input #hf, dataLine
lines = Split(dataLine, vbNewLine)
lines = Split(dataLine, "\n")
lines = Split(dataLine, "CR")
lines = Split(dataLine, "LF")
Close #hf
我也尝试按照thread
进行操作对于喜欢使用dictinary的人来说,这是我的代码:
Set getProjectDictionary = CreateObject("Scripting.Dictionary")
Dim item As String
Dim key As String
Dim dataLine As String
Open FileName For Input As 1
While Not EOF(1)
On Error Resume Next
Line Input #1, dataLine
temp = Split(dataLine, ",")
If Not temp(0) = "" Then
getProjectDictionary.Add temp(0), temp(3)
End If
Wend
Close 1
答案 0 :(得分:2)
我认为这有答案 - 分裂在vbcrlf上?
在你给出的4个例子中," CR"和" LF"会寻找文字字符串" CR"和" LF",这不是你想要的。 VB没有认识到" \ n"像大多数类C语言一样,所以这样就出来了。 vbnewline最接近工作,但我认为这可能会对你有所帮助:
http://www.jaypm.com/2012/08/the-difference-between-vbcrlf-vbnewline-and-environment-newline/
答案 1 :(得分:2)
您附带的屏幕截图显示该文件使用CR LF作为换行符,但我从Google云端硬盘链接下载的文件实际上仅使用LF,因此您可能希望使用:
lines = Split(dataLine, vbLf)
此外,该文件使用带有BOM的Little Endian UCS-2编码。如果您只是使用Open
语句打开文件,则可能会遇到损坏的字符和其他编码相关的问题。我建议using Filesystem object instead。
答案 2 :(得分:2)
这是我目前似乎运作良好的代码:
Option Explicit
Sub test()
Dim a As Object
Set a = getPropertiesDictionary("c:\Temp\Creo\param_table.csv")
Debug.Print a.item("PTC_WM_CREATED_BY")
End Sub
' populate dictinoary with document types based on input file
Function getPropertiesDictionary(FileName As String) As Object
Set getPropertiesDictionary = CreateObject("Scripting.Dictionary")
Dim temp() As String
Dim dataLine As String
Dim hf As Integer: hf = FreeFile
Dim lines() As String, i As Long
Open FileName For Input As #hf
Line Input #hf, dataLine
lines = Split(dataLine, vbLf)
Close #hf
For i = 0 To UBound(lines) - 1
temp = Split(lines(i), ",")
If Not temp(0) = "" Then
getPropertiesDictionary.Add temp(0), temp(2)
End If
Next
End Function