如何将数据从csv文件导入到xlsm

时间:2019-01-18 14:07:03

标签: excel vba

当前尝试使用命令按钮从CSV文件导入数据。当我运行按钮时,我没有收到任何错误,但是没有打印出任何内容。

Private Sub CommandButton23_Click()
Dim Next_Row As Long
    Next_Row = 1

File = Application.GetOpenFilename _
        ("CSV Files (*.csv), *.csv", , "Select the CSV file", , False)

    If File = False Then
        MsgBox_Response = MsgBox("File could not be opened or is not compatible", vbOKOnly)
        Else
        Open File For Input As #1

        row_number = 1
      Do Until EOF(1)

            Line Input #1, LineFromFile

            LineItems = Split(LineFromFile, ",")
          Loop
          End If

        row_number = row_number + 1
        Debug.Print LineFromFile
    Close #1

End Sub

我想将csv文件中的所有数据打印到另一个工作表上,在该工作表中我设置了一些宏。

1 个答案:

答案 0 :(得分:0)

我认为您的代码结构错误

Dim File As Variant
Dim MsgBox_Response As Long
Dim LineFromFile As String
Dim LineItems As Variant
Dim RowCounter As Long

File = Application.GetOpenFilename _
("CSV Files (*.csv), *.csv", , "Select the CSV file", , False)

If File = False Then
    MsgBox_Response = MsgBox("File could not be opened or is not compatible", vbOKOnly)
Else
    Open File For Input As #1

    ' Update this with your sheet reference
    With Sheet1
        Do Until EOF(1)
            Line Input #1, LineFromFile

            LineItems = Split(LineFromFile, ",")
            ' Increment row counter
            RowCounter = RowCounter + 1
            .Range("A" & RowCounter).Resize(, UBound(LineItems) + IIf(LBound(LineItems) = 0, 1, 0)).Value2 = LineItems
            Debug.Print Join(LineItems, vbTab)
        Loop
    End With
    Close #1
End If