通过VBA将.CSV文件导入和过滤到Excel中

时间:2015-02-01 20:35:54

标签: excel vba excel-vba csv import

我尝试从.csv导入Excel电子表格中的几(20)列数据,同时在导入时清理数据。

我是使用VBA在Excel中执行任何操作的新手。我的编码经验仅限于大学后面的一点VB,所以我掌握了这个想法。我愿意投入时间和精力,甚至购买几本书(任何建议?)。

.csv文件如下所示:

Job:JS_010815_HEASB,Version:2.40,Units:USSurveyFeet,,,,,,,,,,,,,,,,,
PS1457,17262086.61,711051.298,509.153,CONTROL POINT,,,,,,,,,,,,,,,
JS2924,17262069.42,711898.13,505.726,CKP,CKP:POINT ID,PS7431,CKP:NOTES,,,,,,,,,,,,
PS7431,17262069.36,711898.141,505.705,CP,CP:STYLE,PRIM. CONTROL,CP:TYPE,60D NAIL,CP:SIZE,,CP:CONDITION,UNDISTURBED,CP:PROTECTION,OTHER (SEE NOTES),CP:NOTES,,,,
CD7,17262018.81,711181.868,508,PI,,,,,,,,,,,,,,,
CD8,17262889.87,711158.429,510,PI,,,,,,,,,,,,,,,
PS2337,17258986.57,711490.088,506.345,PI,,,,,,,,,,,,,,,
CD5,17262001.04,711782.507,500,PI,,,,,,,,,,,,,,,
JS2925,17261586.74,711741.759,502.677,WELD,WELD:TYPE,MAIN LINE,WELD:XRAY#,BML-901,WELD:JOINT# AHEAD,1708,WELD:JNT HD HEAT#,M75460,WELD:JOINT # BEHIND,1709,WELD:JNT BK HEAT#,M75460,WELD:STATION,716+59,WELD:NOTES
JS2926,17261586.56,711746.613,507.221,NG,NG:REMARKS,4.5 COV,,,,,,,,,,,,,
JS2927,17261628.59,711745.877,502.167,WELD,WELD:TYPE,TIE IN,WELD:XRAY#,BTI-028,WELD:JOINT# AHEAD,1724,WELD:JNT HD HEAT#,M75455,WELD:JOINT # BEHIND,1708,WELD:JNT BK HEAT#,M75460,WELD:STATION,717+01,WELD:NOTES
JS2928,17261670.4,711749.899,501.692,WELD,WELD:TYPE,MAIN LINE,WELD:XRAY#,BML-926,WELD:JOINT# AHEAD,1725,WELD:JNT HD HEAT#,M75455,WELD:JOINT # BEHIND,1724,WELD:JNT BK HEAT#,M75455,WELD:STATION,717+43,WELD:NOTES

我需要做的两件事是:

  1. 删除":"以及每个单元格中的任何内容。

  2. (次要)我想获取单元格A1中的信息,即Job:JS_010815_HEASB,并将其插入每行的末尾。

1 个答案:

答案 0 :(得分:1)

我建议最简单的方法是将其拆分为各个部分:

  1. 导入(不确定是否要自动化,但如果您这样做,我已经包含说明。)
  2. 过滤细胞,删除":"
  3. 将单元格A1复制到结束(或移动列A,不确定)
  4. 导入

    导入非常简单,可以使用以下内容完成:

    Sub importCSV(file As String, wsName As String)
        Dim connection As String
        connection = "TEXT;" + file
        With Worksheets(wsName).QueryTables.Add(Connection:=connection, Destination:=Worksheets(wsName).Range("A1"))
            .Name = file
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .RefreshStyle = xlOverwriteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = 437
            .TextFileStartRow = 1
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = False
            .TextFileTabDelimiter = False
            .TextFileSemicolonDelimiter = False
            ' If you were using a file with some other type of delimeter, you'd set this to false and then that one to true
            .TextFileCommaDelimiter = True
            .TextFileSpaceDelimiter = False
            .Refresh BackgroundQuery:=False
        End With
    End Sub
    

    file是文件(包括目录),wsName是您要导入的工作表的名称。

    过滤

    要过滤细胞,请尝试以下操作:

    Sub filter(wsName As String)
        Dim c As Range
        For Each c In Worksheets(wsName).usedRange.Cells
            c.value = Right(c.value, Len(c.value) - InStr(c.value, ":"))
        Next
    End Sub
    

    这样做是为了遍历给定工作表的usedRange中的每个单元格(其中wsName是工作表的名称)并将对象c设置为它。然后我们可以简单地将c.value设置为我们想要的任何新值,在我们的示例中,是:右边的所有内容。

    为此,我们使用Right()函数,stringinteger length,并从右侧返回多个字符。要计算出我们想要的字符数,我们会使用Len()获取整个字符串的长度,并从中减去:InStr()之间的字符数。< / p>

    InStr()返回角色的位置,如果它在那里,或0,这意味着如果角色不在那里,我们将调用{{1}使用字符串的长度,所以它只返回完整的输入。)

    复制

    不完全确定你要去的地方。如果您尝试移动整个列,请使用:

    Right()

    其中Sub moveColumnToEnd(wsName As String, colNum As Integer) Dim columnCount As Integer With Worksheets(wsName) columnCount = .UsedRange.Columns.Count .Columns(colNum).Cut .Columns(columnCount + 1).Insert End With End Sub 是工作表的名称,wsName是要移动的列的编号(在您的情况下为1)。希望代码本身非常自我解释。如果没有,请问。

    如果您只想复制Cell colNum,请尝试以下操作:

    A1

    其中Sub copyA1ToEnd(wsName As String) Dim columnCount As Integer Dim rowCount As Integer Dim copyRange As Range Dim c As Range With Worksheets(wsName) columnCount = .UsedRange.Columns.Count rowCount = .UsedRange.Rows.Count ' What we're doing here is getting the range from the first cell of the last column+1 ' all the way to the bottom most cell of that column. The Cells() command takes it's ' arguments (row, col) not (X, Y) like you'd probably expect. Set copyRange = .Range(.Cells(1, columnCount + 1), .Cells(rowCount, columnCount + 1)) ' Again, like in the filter function, we loop through each cell in the range and set ' it to what we want it to be For Each c In copyRange.Cells c.Value = .Range("A1").Value Next End With End Sub 是工作表的名称。再次,希望它是非常自我解释的。