MS Excel VBA - 除了最后 4 行之外,代码运行完美

问题描述 投票:0回答:1

我的代码可以运行除 4 行之外的所有内容。

我的 Excel VBA 代码可以完美运行并执行其应该执行的操作,但最后 4 行向上移动了 2 行。这意味着应该在最后一行的数据在倒数第三行。

此代码应获取一个电子表格中的数据,根据 A 列是否有数据隐藏所有空行,然后将此数据映射到同一工作簿中的另一个电子表格,该工作簿是来自 Xero 会计软件的模板。

Sub MapDataToXeroTemplate4()
    Dim wsSource As Worksheet
    Dim wsTemplate As Worksheet
    Dim lastRow As Long
    Dim lastColSource As Long
    Dim lastColTemplate As Long
    Dim i As Long
    Dim j As Long
    Dim col As Long

    ' Set your source and template sheets
    Set wsSource = ThisWorkbook.Sheets("Budget Manager Overall Budget") ' Change to your source sheet name
    Set wsTemplate = ThisWorkbook.Sheets("Overall Budget") ' Change to your Xero template sheet name
    
    ' Find the last row with data in the source sheet (Column A)
    lastRow = wsSource.Cells(wsSource.Rows.Count, "A").End(xlUp).Row
    
    ' Find the last column with data in the source sheet and template sheet
    lastColSource = wsSource.Cells(1, wsSource.Columns.Count).End(xlToLeft).Column
    lastColTemplate = wsTemplate.Cells(1, wsTemplate.Columns.Count).End(xlToLeft).Column
    
    ' Reset row in template where data starts
    j = 2 ' Assuming row 1 in the template contains headers

    ' Loop through the source sheet and hide rows without values in column A
    For i = 2 To lastRow ' Assuming the first row is headers, start from row 2
        If IsEmpty(wsSource.Cells(i, 1).Value) Then
            wsSource.Rows(i).Hidden = True
        Else
            wsSource.Rows(i).Hidden = False
        End If
    Next i

    ' Loop through the source sheet and map to the Xero template
    For i = 2 To lastRow ' Assuming row 2 onwards has data
        If Not wsSource.Rows(i).Hidden Then
            ' Dynamically map columns from source to template
            For col = 1 To Application.Min(lastColSource, lastColTemplate) ' Map up to the minimum number of columns
                wsTemplate.Cells(j, col).Value = wsSource.Cells(i, col).Value
            Next col
            
            ' Increment j only after mapping the current row
            j = j + 1
        End If
    Next i
    
    MsgBox "Data mapping completed!"
End Sub

如果您知道为什么下面 4 行会出现该问题,请提供帮助。我无法共享这些文件,因为它包含敏感数据,但我认为可以创建虚拟文件。

excel vba
1个回答
0
投票

在隐藏数据后,根据我对循环的评论进行构建。 您可以完成确定

wsSource.Rows(i).Hidden
的循环,然后简单完成:

Dim colNum as Long:  colNum = Application.Min(lastColSource, lastColTemplate)
With wsSource
    .Range(.Cells(2,1),.Cells(lastRow,colNum)).SpecialCells(xlCellTypeVisible).Copy
End with
With wsTemplate
    .Range(.Cells(2,1),.Cells(lastRow,colNum)).PasteSpecial xlPasteValues
End with
© www.soinside.com 2019 - 2024. All rights reserved.