【发布时间】:2017-03-25 10:39:19
【问题描述】:
我从 VBA 和编程开始。
我有一个包含 X 值的电子表格。这些值中的每一个都与文件夹中的 .xml 文件匹配(或不匹配)(该值存在于 xml 标题中)。 我需要的是,对于这些值中的每一个,我的程序都会搜索一个匹配的 .xml 文件,并在电子表格中的值旁边写上“找到”或“未找到”。
到目前为止我的代码:
Sub StringExistsInFile()
Dim theString As String
Dim path As String
Dim StrFile As String
Dim fso As New FileSystemObject
Dim file As TextStream
Dim line As String
theString = Sheets("PHILA_RESULT_PART_201703210429").Cells(i + 1, 2).Value
path = "C:\Users\Jira\Desktop\LaPoste\20170324_120939_export_phila_commande.Envoi1\"
StrFile = Dir(path & "*.xml")
i = 1
Do While StrFile <> ""
Set file = fso.OpenTextFile(path & StrFile)
Do While Not file.AtEndOfLine
line = file.ReadLine
If InStr(1, line, theString, vbTextCompare) > 0 Then
Sheets("PHILA_RESULT_PART_201703210429").Cells(i + 1, 14).Value = "found"
i = i + 1
Exit Do
End If
Loop
file.Close
Set file = Nothing
Set fso = Nothing
StrFile = Dir()
Loop
End Sub
感谢您的帮助。
值如何存储在电子表格中:
蓝色 = 我搜索的值。 红色 = 我想写“找到”或“未找到”的地方。
编辑:
在一些“改进”之后有我的代码
Sub StringExistsInFile()
Dim theString As String
Dim path As String
Dim StrFile As String
Dim fso As New FileSystemObject
Dim file As TextStream
Dim line As String
theString = Sheets("PHILA_RESULT_PART_201703210429").Cells(i + 1, 2).Value
path = "C:\Users\Jira\Desktop\LaPoste\20170324_120939_export_phila_commande.Envoi1\"
StrFile = Dir(path & "*.xml")
i = 1
Do While Sheets("PHILA_RESULT_PART_201703210429").Cells(i + 1, 2).Value <> ""
Set file = fso.OpenTextFile(path & StrFile)
Do While Not file.AtEndOfLine
line = file.ReadLine
If InStr(1, line, theString, vbTextCompare) > 0 Then
Sheets("PHILA_RESULT_PART_201703210429").Cells(i + 1, 14).Value = "found"
Else
Sheets("PHILA_RESULT_PART_201703210429").Cells(i + 1, 14).Value = "not found"
End If
Loop
i = i + 1
file.Close
Set file = Nothing
StrFile = Dir()
Loop
设置 fso = 无 结束子
【问题讨论】:
-
您有什么问题?顺便说一句,将
Set fso = Nothing移到End Sub之前 -
嗨。我的问题是它在“N”列中“找到”了 74 次(我的文件夹中有 74 个文件)。所以我想治疗是正确的,但不是我写结果的方式。如果我回顾一下我的需求:我搜索“B2”中的值是否存在于我的 .xml 文件之一中,如果是,我在“N2”中写“找到”,而不是在“N2”中写“未找到”。如果 "BX" "".,我对电子表格的每一行都执行此操作
-
预期的结果是什么?
-
如果一个xml文件与“B2”中的值匹配,我在“N2”中写“找到”,如果不匹配我写“未找到”。我对电子表格的每一行都执行此操作。
-
为什么74个“找到”不好?