Excel vbNewline vs Chr(10)作为Windows与Mac OSX中的换行符分隔符
我有一个Excel sub,它使用Excel vbNewline vs Chr(10)作为Windows与Mac OSX中的换行符分隔符,excel,vba,compatibility,Excel,Vba,Compatibility,我有一个Excel sub,它使用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/Wind
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
其他人注意到了这一点/有什么解释吗?正如John在评论中提到的,这两种操作系统具有不同的换行符 因此,在拆分之前,请检查存在哪个字符,然后拆分它。比如说
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
如果需要支持多个操作系统(或同一操作系统上的不同版本),可以查看条件编译语句 您可以参考以下内置编译器常量列表: 将分隔符变量定义为字符串,并将其指定为函数的结果
Dim dlmt as String
dlmt = newLine()
fullArray = Split(CSV, dlmt)
然后,该函数使用条件编译常量检查操作系统:
Function newLine() As String
#If Win32 Or Win64 Then
ret = Chr(10)
#ElseIf Mac Then
ret = vbNewLine
#End If
newLine = ret
End Function
坦白地说,现在我这么做了,我记得这里不一定要使用条件编译,除非您有一些在某些版本中不会编译的方法/属性。您可以使用更简单的应用程序属性。OperatingSystem
:
Function newLine() As String
Select Case Application.OperatingSystem
Case Like "Windows*"
ret = Chr(10)
Case Else
ret = vbNewLine
End Select
End Function
类似“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
你不知道这两个操作系统有不同的换行符吗?不,我一点都不熟悉。我最近刚搬到Mac。我需要这个潜艇有良好的可比性,虽然。您能为我指出正确的方向吗?您应该能够成功地使用
Environment.NewLine
来获得特定于平台的新线组合。。假设Mono正确地实现了它(我假设它是…)。如果您需要支持多个操作系统(或同一操作系统上的不同版本),您可以查看条件编译语句。@SimonWhitehead:它是VBA,不是VB.NETI认为存在vbNewLine
,这样你就可以在Mac上使用它并获得胜利,它会为你所在的系统返回正确的换行符。否则,与其他常量相比,有什么意义呢?@Dick Kusleika,你的正确,但它还没有在VBACurious中全面实现,谁会投票否决它而不留下任何解释,但不管怎样……可能是因为像这样的案例无效,就像现在一样。