Sub TestWriteXML() Dim FFileA As Long Dim exeFile As String FFileA = FreeFlie Open "c:\Users\hp\Desktop\code\exefiles.xml" For Output As #FFileA Print #FFileA, "<?xml version=""1.0""?>" Print #FFileA, "<?mso-application progid=""Excel.sheet""?>""" Print #FFileA, "<Workbook xmlns=""urn:schemas-microsoft-" & "com:office:spreadsheet"">" Print #FFileA, " <Worksheet ss:Name=""EXE Files"">" Print #FFileA, " <Table>" exeFile = Dir("C:\Users\hp\Desktop\code\*.txt") While exeFile <> "" Print #FFileA, " <Row>" Print #FFileA, " <Cell><Data ss:Type=""String"">" & "</Data></Cell>" Print #FFileA, " <Cell><Data ss:Type=""String"">" & FileDateTime("C:\Users\hp\Desktop\cod\" & exeFile) & "</Data></Cell>" Print #FFileA, " <Row>" exeFile = Dir Wend Print #FFileA, " </Table>" Print #FFileA, " </Worksheet>" Print #FFileA, " </Workbook>" Close #FFileA End Sub
这是《学习MS VBA》书中第九章的例子,我将目录名改成了本机上的目录。
运行后显示问题。
然后我想可能是修改了目录名的原因,所以我找到了书配光盘里的代码再运行,发现这问题依然存在。(下面是光盘中的代码)
Sub TestWriteASCIIE() Dim FFileA As Long Dim exeFile As String FFileA = FreeFile Open "c:\exefiles.xml" For Output As #FFileA Print #FFileA, "<?xml version=""1.0""?>" Print #FFileA, "<?mso-application progid=""Excel.Sheet""?>""" Print #FFileA, _ "<Workbook xmlns=""urn:schemas-microsoft-com:office:spreadsheet"">" Print #FFileA, " <Worksheet ss:Name=""EXE Files"">" Print #FFileA, " <Table>" exeFile = Dir("C:\Windows\System32\*.exe") While exeFile <> "" Print #FFileA, " <Row>" Print #FFileA, _ " <Cell><Data ss:Type=""String"">" & exeFile & "</Data></Cell>" Print #FFileA, _ " <Cell><Data ss:Type=""String"">" & _ FileDateTime("C:\Windows\System32\" & exeFile) & "</Data></Cell>" Print #FFileA, " </Row>" exeFile = Dir Wend Print #FFileA, " </Table>" Print #FFileA, " </Worksheet>" Print #FFileA, "</Workbook>" Close FFileA End Sub
请教各位老师是什么问题呢?
VBA中的Open File For Output需要指定的文件事先存在。同时,由于Windows7之后对C盘安全性的要求,C:\下的文件默认应该没有写的权限。
【对策】:您可以在D:\下手工创建一个exefiles.xml,然后将你代码中的c:\exefiles.xml改为d:\exefiles.xml就可以了。我测试是通过的
【另外】:你自己写的那段代码中FreeFile函数写成FreeFlie了,肯定是错误的。不能生成正确的文件号。
Answer Verified By: 熊浩然
谢谢符老师,我验证了下,确实可行。