【问题标题】:Copying data from *.csv into excel将数据从 *.csv 复制到 excel
【发布时间】:2016-05-22 10:17:19
【问题描述】:

我有一个 csv 文件,其中填充了温度传感器的输出,它包含日期、温度控制器地址、温度传感器 1 值、温度传感器 2 值、热功率、冷功率以及限制和警报状态,这是一个在记事本中打开时添加空格以提高可读性的示例:

2/10/2016 14:52:26.2, 1, 73.9039, 74.89208, 14.63515, 0, F, None, None, None,
2/10/2016 14:52:36.594, 1, 73.75067, 74.86765, 25.21247, 0, F, None, None, None,
2/10/2016 14:52:47.165, 1, 73.66284, 74.83871, 35.95927, 0, F, None, None, None,
2/10/2016 14:52:57.788, 1, 73.59991, 74.79031, 47.17537, 0, F, None, None, None,
2/10/2016 14:53:8.381, 1, 73.54018, 74.75883, 58.62064, 0, F, None, None, None,

但是,如果我在 excel 中打开它,我会得到这种格式:

52:26.2, 1, 73.9039, 74.89208, 14.63515, 0, F, None, None, None
52:36.6, 1, 73.75067, 74.86765, 25.21247, 0, F, None, None, None
52:47.2, 1, 73.66284, 74.83871, 35.95927, 0, F, None, None, None
52:57.8, 1, 73.59991, 74.79031, 47.17537, 0, F, None, None, None
53:08.4, 1, 73.54018, 74.75883, 58.62064, 0, F, None, None, None

我正在尝试在 excel 中使用 vba 从该 csv 文件中提取数据或 基于用户通过文件选择器对话框选择的多个 csv 文件到工作簿中进行绘图。我遇到的问题是日期和时间列没有正确显示。我认为这与我用于数据的格式有关,但我不确定。我使用的格式是

m/d/yyyy h:mm:ss.000

由于某种原因,这是显示在 excel 文件中的数据:

1/0/1900 0:52:26.200, 1, 73.90390, 74.89208, 14.64, 0, F, None, None, None
1/0/1900 0:52:36.600, 1, 73.75067, 74.86765, 25.21, 0, F, None, None, None
1/0/1900 0:52:47.200, 1, 73.66284, 74.83871, 35.96, 0, F, None, None, None
1/0/1900 0:52:57.800, 1, 73.59991, 74.79031, 47.18, 0, F, None, None, None
1/0/1900 0:53:08.400, 1, 73.54018, 74.75883, 58.62, 0, F, None, None, None

我尝试将第一列格式化为具有格式的数字

0.0000000000

然后移动数据,但该列只是空白,因为我必须使用范围数据类型才能更改格式。这是我用来显示文件选择器和移动数据的代码:

    Sub fileDialogStart()

    Dim fd As FileDialog
    Dim vrtSelectedItem As Variant

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    With fd
        If .Show = -1 Then
            For Each vrtSelectedItem In .SelectedItems
                ' Finds the last row in the current workbook
                With ThisWorkbook.Sheets(1)
                    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
                End With
                ' Imports the data from the selected file
                Call importData(vrtSelectedItem)
            Next vrtSelectedItem
        Else
        End If
    End With

    Set fd = Nothing
End Sub

Sub importData(ByVal filePath As String)

    Dim targetWorkbook As Workbook, sourceWorkbook As Workbook
    Dim finalRow As Integer
    'Dim targetData as Range

    Set sourceWorkbook = Workbooks.Open(filePath)

    With sourceWorkbook.Sheets(1)
        ' Finds the number of rows in the file selected from the file picker
        finalRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        ' Stores the first column
        targetData = .Range(.Cells(1, 1), .Cells(finalRow, 1))
    End With

    ' Sets the number format
    'targetData.NumberFormat = "0.0000000000"

    With ThisWorkbook.Sheets(1)
        ' Puts the new data into the current workbook after the last row of data
        ' in case there is already data in the workbook from a previous import
        .Range(.Cells(lastRow, 1), .Cells(lastRow + finalRow - 1, 1)) = targetData
    End With

    With sourceWorkbook.Sheets(1)
        ' Gets the rest of the data from the file selected
        sourceData = .Range(.Cells(1, 2), .Cells(finalRow, 10))
    End With

    With ThisWorkbook.Sheets(1)
        ' Puts the rest of the data into the current workbook
        .Range(.Cells(lastRow, 2), .Cells(lastRow + finalRow - 1, 10)) = sourceData
    End With

    sourceWorkbook.Save
    ThisWorkbook.Save
    sourceWorkbook.Close False
End Sub

fileDialogStart() sub 在最开始用于绘图的 sub 中被调用,我在导入数据后将整个第一列的格式设置回 m/d/yyy h:mm:ss.000。也许问题与我将 csv 文件作为工作簿打开这一事实有关?我不知道。任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 您希望日期和时间在单个单元格中还是在相邻单元格中??
  • @Gary'sStudent 单个单元格
  • @Gary'sStudent 我编辑了这个问题以反映我刚刚发现的一些东西,如果我在 excel 而不是记事本中打开 csv 文件,它的格式会有所不同。记事本格式是正确的
  • @Logan - 如果您通过功能区 UI 中的 Data>Get External Data>From Text 导入 csv 文件,我很好奇日期值是如何输入的(您可以在其中调整分隔符)。
  • @ScottHoltzman 我刚刚检查过,数据的输入方式与我刚刚在 excel 中打开文件的方式相同

标签: excel csv vba


【解决方案1】:

Workbooks.OpenText method 允许您指定每个字段的TextFileColumnDataTypes property。这相当于Range.TextToColumns method。为第一个字段指定 xlMDYFormat 格式足以正确输入日期时间(包括它们的秒数)。

Sub openCSV()
    Dim fp As String, fn As String, wbCSV As Workbook

    fp = Environ("TMP")
    fn = "datetemp.csv"
    Debug.Print fp & Chr(92) & fn
    Workbooks.OpenText Filename:=fp & Chr(92) & fn, DataType:=xlDelimited, _
                       Tab:=False, Semicolon:=False, Space:=False, _
                       Other:=False, Comma:=True, FieldInfo:=Array(1, xlMDYFormat), _
                       Local:=True
    With ActiveWorkbook
        With Worksheets(1)
            With .Columns(1)
                .NumberFormat = "mm/dd/yyyy  hh:mm:ss.000"
                .AutoFit
            End With
        End With
    End With

End Sub

根据您自己的区域设置,可能不需要Local:=True。它适用于我的 EN-US 默认设置。

【讨论】:

  • 从资源管理器文件夹窗口中双击 CSV 只是不是将数据放入工作表的可靠方法。 Data ► Get External Data ► From Text 是另一个使用 QueryTables.Add 方法的方法,该方法与 FieldInfo 参数的选项相同,但我发现 Workbooks.OpenText method 最适合我的目的。跨度>
  • 这很完美!唯一的问题是我最后仍然没有得到几分之一秒,它们显示为全 0,我不确定为什么会发生这种情况
  • 好的,我想出了如何获取毫秒数,我将.NumberFormat = "mm/dd/yyyy hh:mm:ss.000" 更改为.NumberFormat = "0.0000000000",然后将其改回导入后的日期和时间。谢谢!
【解决方案2】:

Excel 正在做一些奇怪的事情;但是当我运行这个时:

Sub WTF()
   Dim FilesToOpen
   Dim wf As WorksheetFunction
   Set wf = Application.WorksheetFunction
   Dim ary, bry, DQ As String
   DQ = Chr(34)

   FilesToOpen = Application.GetOpenFilename _
      (FileFilter:="Text Files (*.csv), *.csv", Title:="Text Files to Open")

   Close #1
   Open FilesToOpen For Input As #1

   j = 1
   Do While Not EOF(1)
      Line Input #1, TextLine
      ary = Split(TextLine, ",")
      bry = Split(ary(0), " ")
         Cells(j, 1).Formula = "=datevalue(" & DQ & bry(0) & DQ & ")+timevalue(" & DQ & bry(1) & DQ & ")"
         Cells(j, 1).NumberFormat = "mm/dd/yyyy hh:mm:ss.000"
         For k = 2 To 10
            Cells(j, k) = ary(k - 1)
         Next k
      j = j + 1
   Loop

   Close #1
End Sub

根据您发布的数据,我得到:

我无法解释的是,为什么 Excel 在直接打开文件方面做得这么差。

也许其他人可以解释这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    相关资源
    最近更新 更多