【发布时间】:2015-07-06 09:54:00
【问题描述】:
我试图只返回两个作者:“Ralls, Kim”和“Boal, John”。问题是“Ralls, Kimberly”也符合我的标准。有没有办法设置一个“精确”的项目匹配,这样我就可以避免这种情况?
<?xml version="1.0"?>
<catalog>
<book id="Adventure">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<price>44.95</price>
</book>
<book id="Science-Adventure">
<author>Ralls, Kimberly</author>
<title>Midnight Rain</title>
<price>5.95</price>
</book>
<book id="Adventure">
<author>Boal, John</author>
<title>Mist</title>
<price>15.95</price>
</book>
<book id="Mystery">
<author>Ralls, Kim</author>
<title>Some Mystery Book</title>
<price>9.95</price>
</book>
</catalog>
使用此代码:
Sub mySub()
Dim XMLFile As MSXML2.DOMDocument
Dim Author As Variant
Dim athr As String, BookType As String, Title As String
Dim AuthorArray() As String, BookTypeArray() As String, TitleArray() As String
Dim i As Long, x As Long, j As Long
Dim mainWorkBook As Workbook
Dim n As IXMLDOMNode
Set mainWorkBook = ActiveWorkbook
Set XMLFile = CreateObject("Microsoft.XMLDOM")
XMLFile.Load ("vba.xml")
x = 1
j = 0
Set Author = XMLFile.SelectNodes("/catalog/book/author")
For i = 0 To (Author.Length - 1)
ReDim Preserve AuthorArray(0 To i)
ReDim Preserve BookTypeArray(0 To i)
ReDim Preserve TitleArray(0 To i)
athr = Author(i).Text
BookType = Author(i).ParentNode.getAttribute("id")
Title = Author(i).ParentNode.getElementsByTagName("title").Item(0).nodeTypedValue
If athr = "Ralls, Kim" or athr = "Boal, John" Then
AuthorArray(j) = athr
BookTypeArray(j) = BookType
TitleArray(j) = Title
j = j + 1
x = x + 1
End If
Next
Range("A3:A" & UBound(AuthorArray) + 1) = WorksheetFunction.Transpose(AuthorArray)
Range("B3:B" & UBound(BookTypeArray) + 1) = WorksheetFunction.Transpose(BookTypeArray)
Range("C3:C" & UBound(BookTypeArray) + 1) = WorksheetFunction.Transpose(TitleArray)
End Sub
【问题讨论】:
-
如果它通过名称检查,您还可以检查长度,因此名称和长度必须匹配。
-
是什么让您认为它不起作用? "=" 是 精确比较。这些都不返回 TRUE: If athr = "Ralls, Kimberly" = "Ralls, Kim" Then MsgBox "1" If athr = "Ralls, Kim" = "Ralls, Kimberly" Then MsgBox "2"
-
您可以使用 VBA 的
strComp()来比较字符串。试试If strComp(athr,"Ralls, Kim",0) or strComp(athr,"Boal, John",0) Then...之类的东西 另外,每当我尝试使用'=' 或'strComp()' 比较字符串时,我会先trim()然后使用字符串,以确保不存在可能导致比较失败的空格。athr = trim(athr) -
@CarlKevinson 在你指出这一点之前,我一直在发疯。我正在处理一个更大的文件,并且无法逐行处理每个输出。感谢您的完整性检查。
标签: xml vba excel dom xml-parsing