用 & 替换 & 使用 VBA

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23922510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:17:58  来源:igfitidea点击:

Replace & with & using VBA

xmlvba

提问by Michael St Clair

Is there a way to find &in the file I am creating with VBA and replace it with &?

有没有办法&在我用 VBA 创建的文件中找到并替换它&

Here is a short snippet of my code to show how I am creating the file.

这是我的代码的一小段,用于展示我是如何创建文件的。

Open myFile For Output As #1

Print #1, "<?xml version=""1.0"" encoding=""UTF-8""?>"

Print #1, "     <name>" & element & "</name>"

Close #1

One of the elements is C&C which is causing my problem.

其中一个元素是 C&C,它导致了我的问题。

回答by Tim Williams

Print #1, "     <name>" & Replace(element, "&", "&amp;")  & "</name>"

回答by Tmdean

If you're generating an XML file, unless you're doing something really simple it might be smarter to use an XML libraryinstead of dealing with a million one off little problems like this.

如果您正在生成一个 XML 文件,除非您正在做一些非常简单的事情,否则使用XML 库而不是处理像这样的一百万个小问题可能更聪明。

'' Add reference to Microsoft XML, v6.0
Dim doc As New MSXML2.DOMDocument
Dim root As MSXML2.IXMLDOMElement
Dim reader As New SAXXMLReader60
Dim writer As New MXXMLWriter60

Set root = doc.CreateElement("name")
root.Text = element
doc.appendChild root

Set reader.ContentHandler = writer
writer.Indent = True
reader.Parse doc

Print #1, writer.Output