我有以下代码在Excel for Mac 2016中使用VBA脚本生成XML文件。不幸的是,似乎无法从Mac Excel VBA生成UTF-8文件。有人建议从Excel VBA中调用AppleScript,我从来没有使用AppleScript,任何有关如何转换Excel下面代码的见解,以调用AppleScript生成UTF-8文件,然后写入它将非常感谢。
Sub createXMLFile()
Dim My_Path1 As String
My_Path1 = MacScript("return (path to desktop folder) as string")
Dim rng1 As Range, rng2 As Range, cl As Range
Set rng1 = ThisWorkbook.Sheets("upload").Range("A2")
Set rng1 = ThisWorkbook.Sheets("upload").Range(rng1, rng1.End(xlDown))
Dim strPath As String
strPath = "cancel_reasons"
Dim fnum As Integer
fnum = FreeFile()
Open My_Path1 & Trim(strPath) & ".xml" For Output As #fnum
Print #fnum, "<?xml version=""1.0""?>"
Print #fnum, "<x:cancelShiftReasons xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation=""urn:cancelShiftReasons ./cancelshiftreasonmaster.xsd"" xmlns:x=""urn:cancelShiftReasons"">"
For Each cl In rng1
Call write_xml_line_2(cl, fnum)
Next cl
Print #fnum, "</x:cancelShiftReasons>"
Close #fnum
End Sub
答案 0 :(得分:0)
在Applescript中,您只需在编写数据时指定为“class utf8”。总的来说,AS中的步骤与您的VBA步骤非常相似。
因为脚本用完了Excel,我添加了一个“try”块(类似于VBA的“on error”)来检查Excel文档中的行数。如果没有文档打开,则脚本会停止并显示一条消息。我添加了很多评论来说清楚。
set H1 to "<?xml version=\"1.0\"?>" -- to insert " in Applescript, you must escape it by adding \ before
set H2 to "<x:cancelShiftReasons xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation=\"urn:cancelShiftReasons ./cancelshiftreasonmaster.xsd\" xmlns:x=\"urn:cancelShiftReasons\">"
set H3 to "</x:cancelShiftReasons>"
set MyPath to (path to desktop folder) as string
set myFile to "cancel_reasons1.xml"
try -- try to count number of rows in the range
tell application "Microsoft Excel" to set NbRows to count of rows of used range of active sheet -- assume that no empty rows in middle
on error
display dialog "Error : Impossible to count rows" -- may be no Excel document open,...
return
end try
set fnum to open for access file (MyPath & myFile) with write permission
set eof of fnum to 0 --> empty file contents if already exists
write (H1 & return) to fnum as «class utf8»
write (H2 & return) to fnum as «class utf8»
repeat with I from 2 to (NbRows + 1) -- loop through cells starting from A2
tell application "Microsoft Excel" to set Cl to value of range ("A" & I & ":A" & I) of active sheet
write (Cl & return) to fnum as «class utf8» -- write value of the cell I
end repeat
write H3 to fnum as «class utf8» -- not sure if return is required at end of xml ?
close access funm
我对最后一行的xml文件有疑问:不确定最后是否需要返回。如果需要,只需像其他“写”行一样添加返回。