简体   繁体   English

VBA-Excel-解析CSV并遍历每一行

[英]VBA - Excel - Parse CSV and iterate through each row

Sub CopyData()

Dim wb As Workbook
Dim wsDest As Worksheet
Dim sFilePath As String
Dim aData As Variant

sFilePath = Application.GetOpenFilename("CSV Files, *.csv", MultiSelect:=False)
If sFilePath = "False" Then Exit Sub    'Pressed cancel

Set wb = ActiveWorkbook
Set wsDest = wb.Sheets("Sheet2")

Application.ScreenUpdating = False
With Workbooks.Open(sFilePath)
    aData = .Sheets(1).Range("A1", .Sheets(1).Cells(.Sheets(1).Rows.Count, "F").End(xlUp)).Value
    .Close False
End With
Application.ScreenUpdating = True

With wsDest.Range("B11").Resize(UBound(aData, 1), UBound(aData, 2))
    .Value = aData
    .Resize(, 1).NumberFormat = "mm/dd/yyyy"    'Can set date format here, change to dd/mm/yyyy if needed
End With

End Sub

Above is a sample code to copy data from one workbook to another. 上面是一个示例代码,用于将数据从一个工作簿复制到另一个工作簿。

I want to be able to copy specific cells on specific rows that comply with an IF operator, and for that I want to be able to iterate through each row of the CSV file that is being opened to apply the logical operators. 我希望能够复制符合IF运算符的特定行上的特定单元格,为此,我希望能够遍历正在打开以应用逻辑运算符的CSV文件的每一行。

How can the above code be modified to achieve that? 上面的代码如何修改才能实现?

I'm not very good with VBA. 我对VBA不太满意。

The simple and "standard" way is to apply an AutoFilter on the source and copy the visible range. 简单和“标准”的方法是在源上应用自动AutoFilter并复制可见范围。

Sub CopyData()
    Dim wsDest As Worksheet: Set wsDest = ThisWorkbook.Sheets("Sheet2")
    Dim sFilePath As String: sFilePath = Application.GetOpenFilename("CSV Files, *.csv", MultiSelect:=False)
    If sFilePath = "False" Then Exit Sub    'Pressed cancel
    Application.ScreenUpdating = False
    On Error GoTo Cleanup

    With Workbooks.Open(sFilePath).Sheets(1)
        With .Range("A1", .Cells(.Rows.Count, "F").End(xlUp))
            .AutoFilter 1, ">" & CDate("1/1/2017") ' <-- Captures dates since year 2017 for example
            .SpecialCells(xlCellTypeVisible).Copy
        End With
        wsDest.Range("B11").PasteSpecial
        wsDest.Columns("B").NumberFormat = "mm/dd/yyyy"
        .Parent.Close False
    End With

Cleanup:
    Application.ScreenUpdating = True
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM