宏,将数据从文件夹导入到Excel文档中。

huangapple go评论90阅读模式
英文:

Macro that import data from a folder to an excel doc

问题

I'm here to provide you with a Chinese translation of the code you provided. Please note that the code itself is in English, so I'll only translate the comments and any string literals within the code. Here's the translated code:

Sub ImportDataFromNewestATPReportFile()
    Dim mainWorkbook As Workbook
    Dim dataWorkbook As Workbook
    Dim mainWorksheet As Worksheet
    Dim dataWorksheet As Worksheet
    Dim dataFilePath As String
    Dim dataLastRow As Long
    Dim mainLastRow As Long
    Dim dataFilename As String
    Dim newestFile As String
    Dim newestDate As Date

    ' 更新桌面上“ATP报告”文件夹内的数据文件路径
    dataFilePath = Environ("USERPROFILE") & "\Desktop\ATP报告\"

    ' 将dataFilePath变量的值打印到立即窗口
    Debug.Print "文件夹路径:" & dataFilePath

    ' 引用主工作簿和工作表
    Set mainWorkbook = ThisWorkbook
    Set mainWorksheet = mainWorkbook.Sheets("明细行")

    ' 初始化用于存储最新文件信息的变量
    newestDate = Date ' 将初始日期值设置为最小可能日期

    ' 循环遍历文件夹中的文件并找到最新文件
    dataFilename = Dir(dataFilePath & "ATP报告 *.xlsx") ' 搜索以“ATP报告”开头的文件
    Do While dataFilename <> ""
        ' 从文件名中提取日期部分(假设它的格式为“ATP报告yyyymmdd.xlsx”)
        Dim dateString As String
        dateString = Mid(dataFilename, 12, 8) ' 从文件名中提取日期字符串(跳过“ATP报告”前缀)
        Dim fileDate As Date
        On Error Resume Next
        fileDate = DateSerial(CInt(Mid(dateString, 1, 4)), CInt(Mid(dateString, 5, 2)), CInt(Mid(dateString, 7, 2)))
        On Error GoTo 0

        ' 检查提取的日期是否有效且大于当前的newestDate
        If IsDate(fileDate) And fileDate > newestDate Then
            newestDate = fileDate
            newestFile = dataFilename
        End If

        dataFilename = Dir
    Loop

    ' 检查文件夹中是否至少有一个文件
    If newestFile <> "" Then
        ' 打开最新的数据工作簿
        Set dataWorkbook = Workbooks.Open(dataFilePath & newestFile)
        Set dataWorksheet = dataWorkbook.Sheets("ATP报告")

        ' 在数据工作表中找到最后一个包含数据的行
        dataLastRow = dataWorksheet.Cells(dataWorksheet.Rows.Count, "A").End(xlUp).Row

        ' 在主工作表中找到最后一个包含数据的行
        mainLastRow = mainWorksheet.Cells(mainWorksheet.Rows.Count, "A").End(xlUp).Row

        ' 循环遍历主工作表中的每个“物品”
        Dim i As Long
        For i = 2 To mainLastRow ' 假设数据从主工作表的第2行开始
            Dim Item As String
            Item = mainWorksheet.Cells(i, "A").Value ' 假设“物品”在列A中

            ' 在数据工作表中查找“物品”
            Dim j As Long
            For j = 2 To dataLastRow ' 假设数据从数据工作表的第2行开始
                If dataWorksheet.Cells(j, "A").Value = Item Then ' 假设“物品”在列A中
                    ' 将ATP和Intransit数据复制到主工作表的列U和V中
                    mainWorksheet.Cells(i, "U").Value = dataWorksheet.Cells(j, "B").Value ' 假设ATP数据在列B中
                    mainWorksheet.Cells(i, "V").Value = dataWorksheet.Cells(j, "C").Value ' 假设Intransit数据在列C中
                    Exit For ' 找到“物品”后退出内部循环
                End If
            Next j
        Next i

        Application.CutCopyMode = False ' 清除剪贴板

        ' 不保存关闭数据工作簿
        dataWorkbook.Close False
    Else
        MsgBox "在指定的文件夹中找不到数据文件。", vbExclamation
    End If
End Sub

I hope this translation helps you better understand the code. If you have any further questions or need assistance with specific parts of the code, please feel free to ask.

英文:

I am writing a VBA code that automatically fetches the newest ATP report file from the specified folder, extracts relevant data from it, and pastes that data into the "Details-lines" worksheet of the main workbook based on matching "Item" values. However, I receive an error message that there is no data in the specified folder. I created a folder that appears in my desktop named ATP Report and it contains files that get updated daily, every day, a new file will be uploaded named ATP report 20230731 base don the date. What is exactly the problem?

Private Sub Workbook_Open()
    ImportDataFromNewestATPReportFile
End Sub

Sub ImportDataFromNewestATPReportFile()
    Dim mainWorkbook As Workbook
    Dim dataWorkbook As Workbook
    Dim mainWorksheet As Worksheet
    Dim dataWorksheet As Worksheet
    Dim dataFilePath As String
    Dim dataLastRow As Long
    Dim mainLastRow As Long
    Dim dataFilename As String
    Dim newestFile As String
    Dim newestDate As Date

    &#39; Update the folder path for the data files in the &quot;ATP report&quot; folder on your desktop
    dataFilePath = Environ(&quot;USERPROFILE&quot;) &amp; &quot;\Desktop\ATP report\&quot;

    &#39; Print the value of the dataFilePath variable to the Immediate Window
    Debug.Print &quot;Folder Path: &quot; &amp; dataFilePath

    &#39; Set references to the main workbook and worksheet
    Set mainWorkbook = ThisWorkbook
    Set mainWorksheet = mainWorkbook.Sheets(&quot;Details-lines&quot;)

    &#39; Initialize variables to store the information about the newest file
    newestDate = Date &#39; Set an initial date value to the minimum possible date

    &#39; Loop through the files in the folder and find the newest file
    dataFilename = Dir(dataFilePath &amp; &quot;ATP Report *.xlsx&quot;) &#39; Search for files with names starting with &quot;ATP Report&quot;
    Do While dataFilename &lt;&gt; &quot;&quot;
        &#39; Extract the date part from the filename (assuming it is in the format &quot;ATP Report yyyymmdd.xlsx&quot;)
        Dim dateString As String
        dateString = Mid(dataFilename, 12, 8) &#39; Extract the date string from the filename (skipping &quot;ATP Report&quot; prefix)
        Dim fileDate As Date
        On Error Resume Next
        fileDate = DateSerial(CInt(Mid(dateString, 1, 4)), CInt(Mid(dateString, 5, 2)), CInt(Mid(dateString, 7, 2)))
        On Error GoTo 0

        &#39; Check if the extracted date is valid and greater than the current newestDate
        If IsDate(fileDate) And fileDate &gt; newestDate Then
            newestDate = fileDate
            newestFile = dataFilename
        End If

        dataFilename = Dir
    Loop

    &#39; Check if there is at least one file in the folder
    If newestFile &lt;&gt; &quot;&quot; Then
        &#39; Open the newest data workbook
        Set dataWorkbook = Workbooks.Open(dataFilePath &amp; newestFile)
        Set dataWorksheet = dataWorkbook.Sheets(&quot;ATP Report&quot;)

        &#39; Find the last row with data in the data worksheet
        dataLastRow = dataWorksheet.Cells(dataWorksheet.Rows.Count, &quot;A&quot;).End(xlUp).Row

        &#39; Find the last row with data in the main worksheet
        mainLastRow = mainWorksheet.Cells(mainWorksheet.Rows.Count, &quot;A&quot;).End(xlUp).Row

        &#39; Loop through each Item in the main worksheet
        Dim i As Long
        For i = 2 To mainLastRow &#39; Assuming data starts from row 2 in the main worksheet
            Dim Item As String
            Item = mainWorksheet.Cells(i, &quot;A&quot;).Value &#39; Assuming Item are in column A

            &#39; Search for the Item in the data worksheet
            Dim j As Long
            For j = 2 To dataLastRow &#39; Assuming data starts from row 2 in the data worksheet
                If dataWorksheet.Cells(j, &quot;A&quot;).Value = Item Then &#39; Assuming Item are in column A
                    &#39; Copy ATP and Intransit data to columns U and V in the main worksheet
                    mainWorksheet.Cells(i, &quot;U&quot;).Value = dataWorksheet.Cells(j, &quot;B&quot;).Value &#39; Assuming ATP data is in column B
                    mainWorksheet.Cells(i, &quot;V&quot;).Value = dataWorksheet.Cells(j, &quot;C&quot;).Value &#39; Assuming Intransit data is in column C
                    Exit For &#39; Exit the inner loop since the Item is found
                End If
            Next j
        Next i

        Application.CutCopyMode = False &#39; Clear clipboard

        &#39; Close the data workbook without saving
        dataWorkbook.Close False
    Else
        MsgBox &quot;No data files found in the specified folder.&quot;, vbExclamation
    End If
End Sub

I need clarification and help so i can resolve the problem and be able to run the macro successfully.

答案1

得分: 1

我建议将您的代码的各个部分分离出来,放入单独的方法中,这样它们更容易进行测试和重复使用。

例如:获取最新报告的方法

Sub Tester()
    
    Dim latestReport As String
    
    latestReport = NewestReport("C:\Temp\VBA\")
    
    Debug.Print "LatestReport", IIf(Len(latestReport) > 0, latestReport, "Not found")

End Sub

' 在`dataFilePath`中查找最新报告的文件名
Function NewestReport(dataFilePath As String) As String
    Dim newestdate As Date, reportDate As Variant, fName As String, newestFile As String
    fName = Dir(dataFilePath & "ATP Report *.xlsx") ' 搜索以“ATP Report”开头的文件
    Do While fName <> ""
        reportDate = GetReportDate(fName)
        If Not IsEmpty(reportDate) Then
            newestdate = reportDate
            newestFile = fName
        End If
        fName = Dir
    Loop
    NewestReport = newestFile
End Function

' 如果从文件名中提取出有效日期,则返回日期值,否则返回Empty
Function GetReportDate(fileName) As Variant
    Dim rv As Variant
    On Error Resume Next ' 忽略无效日期的错误
    rv = DateSerial(CInt(Mid(fileName, 12, 4)), _
                    CInt(Mid(fileName, 16, 2)), _
                    CInt(Mid(fileName, 18, 2)))
    On Error GoTo 0
    Debug.Print fileName, rv
    GetReportDate = rv
End Function
英文:

I'd suggest pulling out the various parts of your code into separate methods, so they're more-easily testable/re-usable.

Eg: for getting the latest report

Sub Tester()
    
    Dim latestReport As String
    
    latestReport = NewestReport(&quot;C:\Temp\VBA\&quot;)
    
    Debug.Print &quot;LatestReport&quot;, IIf(Len(latestReport) &gt; 0, latestReport, &quot;Not found&quot;)

End Sub

&#39;Find the file name for the newest report at `dataFilePath`
Function NewestReport(dataFilePath As String) As String
    Dim newestdate As Date, reportDate As Variant, fName As String, newestFile As String
    fName = Dir(dataFilePath &amp; &quot;ATP Report *.xlsx&quot;) &#39; Search for files with names starting with &quot;ATP Report&quot;
    Do While fName &lt;&gt; &quot;&quot;
        reportDate = GetReportDate(fName)
        If Not IsEmpty(reportDate) Then
            newestdate = reportDate
            newestFile = fName
        End If
        fName = Dir
    Loop
    NewestReport = newestFile
End Function

&#39;return a Date value if a valid date is extracted from the file name, or Empty if couldn&#39;t get a date
Function GetReportDate(fileName) As Variant
    Dim rv As Variant
    On Error Resume Next &#39;ignore error if not valid date
    rv = DateSerial(CInt(Mid(fileName, 12, 4)), _
                    CInt(Mid(fileName, 16, 2)), _
                    CInt(Mid(fileName, 18, 2)))
    On Error GoTo 0
    Debug.Print fileName, rv
    GetReportDate = rv
End Function

huangapple
  • 本文由 发表于 2023年7月31日 19:19:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76803115.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定