如何在VBA中获取CSV文件中的数据行数

时间:2018-06-26 12:10:46

标签: vba excel-vba excel

我试图在VBA中获取几个CSV文件中的数据行数。 这是代码。

Sub Woo_Products()

Dim fso As New FileSystemObject
Dim flds As Folders
Dim fls As Files
Dim strText As String
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim extfind As String
Dim FilePath As String
Dim sLineOfText As String

On Error Resume Next

Workbooks.Open Filename:="F:\Work\scrape\" & "woocommerce-products.csv", UpdateLinks:=3

Set fls = fso.getfolder("C:\Users\star\Downloads").Files
k = 2
For Each f In fls
    strText = f.Name
    extfind = Right$(strText, Len(strText) - InStrRev(strText, "."))
    If extfind = "csv" Then
        FilePath = "C:\Users\star\Downloads\" & strText

        Open FilePath For Input As #1
        i = 0
        Do Until EOF(1)
            Line Input #1, sLineOfText
            If sLineOfText <> "" Then i = i + 1
        Loop
        Close #1

    End If
Next

Windows("woocommerce-products.csv").Activate
ActiveWorkbook.Save
ActiveWorkbook.Close

End Sub

但是每个文件的计数都相同。 当然,每个文件都有不同的数据行。 希望对我有帮助。

4 个答案:

答案 0 :(得分:2)

如果您需要的只是行数,我将编写一个函数来返回行数。

Function getFileLineCount(FullFileName As String, Optional LineDelimiter As String = vbNewLine) As Long
    Dim text As String
    Dim fileNo As Integer, n As Long
    fileNo = FreeFile
    Open FullFileName For Input As #fileNo
    Do Until EOF(1)
        Line Input #1, text
        n = n + 1
    Loop
    Close #fileNo
    getFileLineCount = n
End Function

答案 1 :(得分:2)

您需要添加参考(工具->参考)

Microsoft Scripting Runtime
Microsoft VBScript Regular Expressions 5.5

这将计算文件中的“ Return&NewLine”字符。

Private Function LineCount(ByVal PathFile As String) As Long
    Dim sData As String
    Dim oFile As New FileSystemObject
    sData = oFile.OpenTextFile(PathFile, ForReading).ReadAll

    Dim oRegX As New RegExp
    oRegX.Pattern = "\r\n"
    oRegX.Global = True
    LineCount = oRegX.Execute(sData).Count + 1

    Set oRegX = Nothing
    Set oFile = Nothing
End Function

答案 2 :(得分:2)

使用FileSystemObject的另一种方法:

Public Function GetLineCount(ByVal Path As String) As Long
    With CreateObject("Scripting.FileSystemObject")
        GetLineCount = UBound(Split(.OpenTextFile(Path, 1).ReadAll, vbNewLine)) + 1
    End With
End Function

答案 3 :(得分:-1)

i = ActiveWorkbook.ActiveSheet.Cells(ActiveWorkbook.ActiveSheet.Rows.Count,1).End(xlUp).Row

效果很好。