我已经获得了以下代码,它从excel工作表中复制内容并将其粘贴到文本文件中并将其另存为html文件。但我需要用UTF-8编码保存它。我在http://www.ozgrid.com/forum/showthread.php?t=154957&p=560424#post560424和Save text file UTF-8 encoded with VBA找到了一些提示,但我无法将此代码实现给我。你能帮我么。 非常感谢!
Private Sub CommandButton1_Click()
Dim FileNum As Integer, cl As Range, z As Integer, y As Integer, FName As String, FPath As String
Dim myStr As String
Dim fsT As Object
FileNum = FreeFile ' next free filenumber
'Open "C:\Temp\TEXTFILE.TXT" For Output As #FileNum ' creates the new file
FPath = "D:\mk"
FName = Sheets("Website_POI").Range("D2").Text & ".html"
Open FPath & "\" & FName For Append As #FileNum
Print #FileNum, [a4]
z = 10
For Each cl In [a4:x3000]
y = cl.Row
If y = z Then
myStr = myStr & "" & cl
'appends the input to an existing file write to the textfile
Else: Print #FileNum, myStr
z = cl.Row
myStr = "": myStr = myStr & "" & cl
End If
Next
'appends the input to an existing file write to the textfile
Print #FileNum, myStr
Close #FileNum ' close the file
End Sub
答案 0 :(得分:3)
使用ADODB.Stream对象,而不是使用I / O Print
语句来编写文件。
我不认为这会附加在现有文件上(如果需要,需要进行一些修改),而不是覆盖现有文件:
myStr = "": myStr = myStr & "" & cl
End If
Next
With CreateObject("ADODB.Stream")
.Type = 2 'Specify stream type - we want To save text/string data.
.Charset = "utf-8" 'Specify charset For the source text data.
.Open 'Open the stream And write binary data To the object
.WriteText myStr
.SaveToFile FPath & "\" & FName, 2 'Save binary data To disk
End With
Close #FileNum
End Sub