看看第一个空行后,我的excel的前几行是空的,但其余的填充

62lalag4  于 2023-03-31  发布在  其他
关注(0)|答案(1)|浏览(117)

我的Excel宏当前连接两列,单位和数字。数字是根据ID拉出来的,有时我希望与单位连接的数字可能不存在于该特定ID。我使用查找最后一行,但在某些情况下不起作用,因为我希望与单位连接的数字仅从第6行开始,有时第8行,但它至少会从第2行开始。第1行包含标题。
我想忽略空行,并且不给它一个查找到第100行的范围,例如,因为我有时可能有超过100行。下面的代码是我目前拥有的,如果列完全填充到最后,它就可以工作。

rowEmpty = 2
    Do While IsEmpty(ws_Export.cells(rowEmpty, 9)) = False
        rowEmpty = rowEmpty + 1
    Loop
    'rowEmpty is now set as the first empty row (sets the range of the table)
    
    'Add units within the same cell as the shunt
    For s = 2 To rowEmpty - 1
        cells(s, 9) = cells(s, 9) & " " & cells(s, 8)
Next s

flvtvl50

flvtvl501#

非空拼接

  • J更换为I,以根据需要进行更换。

Option Explicit

Sub AppendUnits()

    Const WS_NAME As String = "Export"
    Const CAL_FIRST_CELL As String = "I2"
    Const UNIT_COLUMN As String = "H"
    Const DST_COLUMN As String = "J" ' Result
    Const DELIMITER As String = " "
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    Dim ws As Worksheet: Set ws = wb.Sheets(WS_NAME)
    
    Dim crg As Range, rCount As Long
    
    With ws.Range(CAL_FIRST_CELL)
        Dim lCell As Range: Set lCell = .Resize(.Worksheet.Rows.Count _
            - .Row + 1).Find("*", , xlFormulas, , , xlPrevious)
        If Not lCell Is Nothing Then
            rCount = lCell.Row - .Row + 1
            Set crg = .Resize(rCount)
        End If
    End With
    
    If crg Is Nothing Then
        MsgBox "No data found.", vbCritical
        Exit Sub
    End If
    
    Dim urg As Range: Set urg = crg.EntireRow.Columns(UNIT_COLUMN)
    
    Dim cData(), uData()
    
    If rCount = 1 Then
        ReDim cData(1 To 1, 1 To 1): cData(1, 1) = crg.Value
        ReDim uData(1 To 1, 1 To 1): uData(1, 1) = urg.Value
    Else
        cData = crg.Value
        uData = urg.Value
    End If
    
    Dim r As Long, rStr As String
    
    For r = 1 To rCount
        rStr = CStr(cData(r, 1))
        If Len(rStr) > 0 Then
            cData(r, 1) = rStr & DELIMITER & CStr(uData(r, 1))
        End If
    Next r
    
    Dim drg As Range: Set drg = crg.EntireRow.Columns(DST_COLUMN)
    
    drg.Value = cData
    
    MsgBox "Units appended.", vbInformation
    
End Sub

相关问题