首页 > 解决方案 > 使用 VBA 从 csv 文档中删除行

问题描述

所以目前我有以下 VBA 代码,它的作用是从专用目录收集 csv。

Sub UploadData()

' Define the relative variables
Application.ScreenUpdating = False
Application.Calculation = xlManual

' Define the variables necessary
Dim Path As String
Dim DataFile1 As String
Dim datasheet As String
Dim Temp_File_Name1 As String
Dim File_Name1 As String

' Set the path locations to grab the 151_.csv file
Path1 = Worksheets("FileNames").Cells(25, 3).Value
DataFile1 = Worksheets("FileNames").Cells(29, 3).Value

' ------------------------------------------- Send the csv file as an email ------------------------------------------------- '
' Assign the path directory to the csv file
Temp_File_Name1 = Path1 & DataFile1 & "*.csv"
File_Name1 = Dir(Temp_File_Name1)
File_Name1 = Path1 & File_Name1

End Sub

检索到的 CSV 文件采用以下格式,我的目标是删除具有“pipeline_point_code”30000001PC 的行,如下图所示。

在此处输入图像描述

是否可以通过 vba 代码从 csv 中删除这些行?如果没有,我如何将存储在“File_Name1”变量中的这个 csv 粘贴到我的标有“数据”的 Excel 表中

标签: excelvbacsv

解决方案


如果我理解正确,这不是关于读取 .CSV 文件的内容。相反,您想遍历文件夹中的所有文件名,在工作表中列出文件名,然后排除某些文件名,对吗?

您可以使用Dir()不带参数来迭代文件,如下所示:

Dim FileName As String
Dim folder as String
Dim rownum As Integer

' get starting folder
folder = Worksheets("FileNames").Cells(25, 3).Value

' start iterating all files
FileName = Dir(folder + "\*.csv", vbDirectory)
rownum = 1

' iterate all files
Do While FileName <> ""
    ' add to Data sheet, but filter out "pipeline_point_code" file name
    If (FileName <> "pipeline_point_code") Then 
        rownum = rownum + 1
        Worksheets("Data").Cells(rownum, 1).Value = FileName
    End If
    ' next file
    FileName = Dir()
Loop

推荐阅读