VBS字符串编码转换函数代码

因为业务需要将一些字符串转换为指定编码方便后期操作

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Const adTypeBinary = 1
Const adTypeText = 2
 
' accept a string and convert it to Bytes array in the selected Charset
Function StringToBytes(Str,Charset)
  Dim Stream : Set Stream = CreateObject("ADODB.Stream")
  Stream.Type = adTypeText
  Stream.Charset = Charset
  Stream.Open
  Stream.WriteText Str
  Stream.Flush
  Stream.Position = 0
  ' rewind stream and read Bytes
  Stream.Type = adTypeBinary
  StringToBytes= Stream.Read
  Stream.Close
  Set Stream = Nothing
End Function
 
' accept Bytes array and convert it to a string using the selected charset
Function BytesToString(Bytes, Charset)
  Dim Stream : Set Stream = CreateObject("ADODB.Stream")
  Stream.Charset = Charset
  Stream.Type = adTypeBinary
  Stream.Open
  Stream.Write Bytes
  Stream.Flush
  Stream.Position = 0
  ' rewind stream and read text
  Stream.Type = adTypeText
  BytesToString= Stream.ReadText
  Stream.Close
  Set Stream = Nothing
End Function
 
' This will alter charset of a string from 1-byte charset(as windows-1252)
' to another 1-byte charset(as windows-1251)
Function AlterCharset(Str, FromCharset, ToCharset)
  Dim Bytes
  Bytes = StringToBytes(Str, FromCharset)
  AlterCharset = BytesToString(Bytes, ToCharset)
End Function

使用例子:

1
2
3
4
5
dim s1,s2,FromCharset,ToCharset
s1 = "我的字符串之脚本之家"
FromCharset = "GB2312"
ToCharset = "ISO-8859-1"
s2 = AlterCharset(s1,FromCharset,ToCharset)

到此这篇关于VBS字符串编码转换函数代码的文章就介绍到这了,更多相关VBS编码转换内容请搜索代码部落以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码部落


本文章来源于网络,作者是:薛定谔的青蛙王梓,由代码部落进行采编,如涉及侵权请联系删除!转载请注明出处:https://daimabuluo.cc/vbs/264.html

联系我们

在线咨询:点击这里给我发消息

邮件:dick@daimabuluo.cc

遇到问题?请给我们留言

请填写您的邮箱地址,我们将回复您的电子邮件