我有一个Excel子程序,它使用Split()
函数将CSV数据从单元格拆分为数组。但是,根据我使用的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
其他人注意到这个/有解释为什么会这样?
答案 0 :(得分:2)
如果您需要支持多个操作系统(或同一操作系统上的不同版本),您可以查看条件编译语句。
您可以参考此内置编译器常量列表:
http://www.utteraccess.com/wiki/index.php/Conditional_Compilation#Built_In_Compiler_Constants
将分隔符变量定义为字符串,并为其分配函数的结果。
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
答案 1 :(得分:1)
正如John在评论中提到的,这两个操作系统具有不同的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
答案 2 :(得分:0)
“ Windows *”之类的大小写无效。 这对我有用:
' User has Windows or Mac for NewLine
Dim mynewLine As String
If left(Application.OperatingSystem, 7) = "Windows" Then
mynewLine = Chr(10)
Else
mynewLine = vbNewLine
End If