vbNewline与Chr(10)作为Windows与Mac OSX的换行符分隔符

我有一个使用Split()函数将单元格中的CSV数据拆分为数组的Excel子版本。 但是,根据我使用的Excel / OS版本,用作换行符分隔符的字符更改:

Excel 2011 / Mac OSX:

  fullArray = Split(CSV, vbNewLine) 'successfully returns array fullArray = Split(CSV, Chr(10)) 'fails and returns only a single cell 

Excel 2007 / Windows 7:

  fullArray = Split(CSV, Chr(10)) 'successfully returns array fullArray = Split(CSV, vbNewLine) 'fails and returns only a single cell 

其他人注意到这个/有一个解释为什么这是怎么回事?

如果您需要支持多个操作系统(或同一操作系统上的不同版本),则可以查看条件编译语句。

你可以参考这个内build的编译器常量列表:

http://www.utteraccess.com/wiki/index.php/Conditional_Compilation#Built_In_Compiler_Constants

定义你的分隔符variables作为一个string,并为其分配一个函数的结果。

 Dim dlmt as String dlmt = newLine() fullArray = Split(CSV, dlmt) 

该函数然后使用条件编译常量来检查OS:

 Function newLine() As String #If Win32 Or Win64 Then ret = Chr(10) #ElseIf Mac Then ret = vbNewLine #End If newLine = ret End Function 

坦率地说,现在我这样做了,我记得在这里使用条件编译并不是必须的,除非你有一些方法/属性不能在某些版本中编译。 你可以使用Application.OperatingSystem的更简单的属性:

 Function newLine() As String Select Case Application.OperatingSystem Case Like "Windows*" ret = Chr(10) Case Else ret = vbNewLine End Select End Function 

正如约翰在评论中提到的,这两个操作系统有不同的NewLine特性。

因此,在分割之前,请检查是否存在哪个字符,然后将其分割。 例如

 newL = InStr(1, CSV, vbNewLine) vbChrTen = InStr(1, CSV, Chr(10)) If newL > 0 And vbChrTen > 0 Then MsgBox "The string contains both. How would you like to handle it?" ' '~~> Rest of the code ' ElseIf newL > 0 Then fullArray = Split(CSV, vbNewLine) ElseIf vbChrTen > 0 Then fullArray = Split(CSV, Chr(10)) Else MsgBox "The string doesn't contain either of the de-limiters. How would you like to handle it?" ' '~~> Rest of the code ' End If