【问题标题】:Importing csv to Excel, CSV将 csv 导入 Excel、CSV
【发布时间】:2013-07-23 02:28:51
【问题描述】:

我有一个 excel 2007 工作簿,当前工作表名为“a”现在我想要的是,

当用户单击工作表 a 中的按钮时,它应该询问,
要导入哪个 csv 文件,
询问用户想要的新工作表的名称(该 csv 文件的放置位置)。说简化用户现在说“b”。
之后将“工作表 a”复制到新工作表 b 中。 将 csv 导入该新工作表,以逗号分隔,并允许覆盖复制工作表中的现有单元格
完成所有这些任务的基本起始级代码是什么?

我将不胜感激在这方面的任何帮助。

谢谢
萨尔

【问题讨论】:

  • 尝试在录制宏的同时录制宏 - 以此为起点。

标签: vba csv import excel-2007 overwrite


【解决方案1】:

试试这个:

    Public strFile As String

    Sub Main()

    Dim WS As Worksheet

        strFile = Application.GetOpenFilename("Excel workbooks,*.csv*")
        If strFile = "False" Then
            ' the user clicked Cancel
        Else

        y = Right(strFile, Len(strFile) - InStrRev(strFile, "\", -1, vbTextCompare))

        zz = Left(y, InStr(1, y, ".", vbTextCompare) - 1)


        flag = 0
            For k = 1 To Worksheets.Count
                If Sheets(k).Name = zz Then
                    flag = 1
                End If
            Next
                 Set WS = Sheets.Add(After:=Sheets(Worksheets.Count))
            If flag = 0 Then
                 WS.Name = zz
            Else
                MsgBox ("Sheet with same name already exist. Imported to default sheet")
            End If


            importcsv
        End If
    End Sub


    Sub importcsv()
        With ActiveSheet.QueryTables.Add(Connection:= _
            "TEXT;" & strFile, Destination:=Range( _
            "$A$1"))
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .RefreshStyle = xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = 437
            .TextFileStartRow = 1
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = False
            .TextFileTabDelimiter = False
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = True
            .TextFileSpaceDelimiter = False
            .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
            .TextFileTrailingMinusNumbers = True
            .Refresh BackgroundQuery:=False
        End With
    End Sub

【讨论】:

  • & 有没有办法用用户选择的 csv 文件的名称重命名我的新工作表?谢谢萨尔
猜你喜欢
  • 2012-08-06
  • 2013-07-27
  • 2012-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
相关资源
最近更新 更多