我正在运行一个宏,将特定单元格值从电子表格复制到另一个电子表格。这些文件是 csv,以分号分隔,包含通用格式的单元格,包括文字项和数字项。数字项以逗号作为小数点分隔符。该脚本正确导入所有内容,但是,在导入数值时它会忽略逗号。
这是代码:
Public Function importCsv2(strPath As String)
Dim filePath As String
filePath = strPath
Dim fileArray(5, 5) As String
Dim startDate As String
Dim Product As String
Application.DecimalSeparator = ","
If Range("B14").Value <> "" Then
Range("B13").End(xlDown).offset(1, 0).Select
Else:
Range("B13:B" & Range("B" & Rows.Count).End(xlUp).Row).offset(1, 0).Select
End If
currentRow = 0
rowNumber = 0
Open filePath For Input As #1
Do Until EOF(1)
Line Input #1, lineFromFile
fileStr = Split(lineFromFile, vbLf)
Dim item As Variant
For Each item In fileStr
'For item = LBound(fileStr) To UBound(fileStr)
lineitems = Split(item, ";")
'Debug.Print (item)
If rowNumber = 1 Then
startDate = lineitems(6)
Product = lineitems(9)
End If
If rowNumber > 3 And item <> "" Then
If Not doesOfferExist(CStr(lineitems(2))) And CInt(lineitems(0)) <> 0 Then
ActiveCell.offset(currentRow, 0) = startDate
ActiveCell.offset(currentRow, 1) = lineitems(4)
ActiveCell.offset(currentRow, 2) = lineitems(3)
ActiveCell.offset(currentRow, 3) = CDbl(lineitems(6))
ActiveCell.offset(currentRow, 4) = CDbl(lineitems(7))
ActiveCell.offset(currentRow, 5) = lineitems(8)
ActiveCell.offset(currentRow, 6) = lineitems(1)
ActiveCell.offset(currentRow, 7) = lineitems(2)
ActiveCell.offset(currentRow, 8) = "New"
ActiveCell.offset(currentRow, 9) = Product
currentRow = currentRow + 1
End If
End If
Next item
rowNumber = rowNumber + 1
Loop
Close #1
Call setImportLastUpdate
End Function
关键部分是:
ActiveCell.offset(currentRow, 3) = CDbl(lineitems(6))
ActiveCell.offset(currentRow, 4) = CDbl(lineitems(7))
Excel 选项将逗号设置为小数点分隔符。
例如,当导入 84,55 时,我得到的结果是 8455。 我已经添加了
Application.DecimalSeparator = ","
,但并没有解决问题。
有什么帮助吗?提前谢谢你
有点晚了,但供以后参考。
设置 ThousandsSeparator 和 DecimalSeparator,如下所示:
Application.ThousandsSeparator = "."
Application.DecimalSeparator = ","
有同样的问题。通过使用以下辅助函数解决了这个问题:
Function ConvertToDouble(s As String) As Variant
On Error Resume Next ' Temporarily suppress errors for conversion
Dim result As Double
result = CDbl(s) ' Attempt to convert using locale-aware CDbl
If Err.Number <> 0 Then
ConvertToDouble = "" ' Return empty string on failure
Else
ConvertToDouble = result ' Return the converted number
End If
On Error GoTo 0 ' Revert to default error handling
End Function