如何使用 Excel VBA 确定文件编码类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13911580/
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
How to determine file encoding type with Excel VBA
提问by Tyler Durden
I have built an Excel/VBA tool to validate csv files to ensure the data they contain is valid. They csv can come originate from anywhere (from a full blown unix system or a desktop user saving data out from Excel). The Excel tool is sent out to businesses so they can validate their csv files in their own environment and without taking the risk of their data leaving thier systems. Thus, the solution needs to be in native VBA and not link into external libraries.
我已经构建了一个 Excel/VBA 工具来验证 csv 文件,以确保它们包含的数据是有效的。它们 csv 可以来自任何地方(来自完整的 unix 系统或从 Excel 保存数据的桌面用户)。Excel 工具被发送给企业,以便他们可以在自己的环境中验证他们的 csv 文件,而无需冒数据离开他们的系统的风险。因此,解决方案需要在本机 VBA 中,而不是链接到外部库。
So using VBA, I need to be able to automatically detect UTF-8 (with or without BOM) or ANSI file encodings and warn the user if these are not the file encodings used for the csv.
因此,使用 VBA,我需要能够自动检测 UTF-8(带或不带 BOM)或 ANSI 文件编码,如果这些不是用于 csv 的文件编码,则警告用户。
I think this would perhaps involve reading in a few bytes from the start of the file and determining the encoding based on the existance of the byte order mark.
我认为这可能涉及从文件开头读取几个字节并根据字节顺序标记的存在确定编码。
Could you help me get me started on the right track?
你能帮我走上正轨吗?
回答by bonCodigo
Assuming you have the freedom to ask user to choose the correct file type, making them responsible for what they choose as a file ;)
假设您可以自由地要求用户选择正确的文件类型,让他们为自己选择的文件负责;)
That means, you can create a form where users can choose the filename and the encoding type like how we do on file open
wizard.
这意味着,您可以创建一个表单,用户可以在其中选择文件名和编码类型,就像我们在file open
向导中所做的那样。
Else,
别的,
I suggest you to use the FileSystemObject
. It returns a TextStream
which can be utilized to determine the encoding. I doubt VBA supports other types of encoding and please correct me if it does :) and happy to hear. :)
我建议你使用FileSystemObject
. 它返回TextStream
可用于确定编码的 a。我怀疑 VBA 是否支持其他类型的编码,如果支持,请纠正我:) 并且很高兴听到。:)
Here is a link for further considerations:-
这是进一步考虑的链接:-