VBA Sorting of Data

后端 未结 2 1773
深忆病人
深忆病人 2020-12-21 19:51

The problem i run into is that sometimes entire headers and data values are missing in the dataset and therefore using the last row in the script the data

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-21 20:35

    I suggest, rather than copying column by column, you instead copy row by row.

    Public Sub CopyData()
        Dim inputRow As Long
        Dim outputRow As Long
        Dim inputSheet As Worksheet
        Dim outputSheet As Worksheet
    
        Set inputSheet = Worksheets("Sheet1")
        Set outputSheet = Worksheets("Sheet2")
    
        'First, copy the headers
        inputSheet.Rows(1).Copy outputSheet.Rows(1)
    
        'Next, copy the first row of data
        inputSheet.Rows(2).Copy outputSheet.Rows(2)
    
        'Loop through the rest of the sheet, copying the data row for each additional header row
        inputRow = 3
        outputRow = 3
        While inputSheet.Cells(inputRow, 1) <> ""
            inputRow = inputRow + 1 'increment to the data row
            inputSheet.Rows(inputRow).Copy outputSheet.Rows(outputRow)
            inputRow = inputRow + 1 'increment to the next potential header row
            outputRow = outputRow + 1 'increment to the next blank output row
        Wend
    End Sub
    

提交回复
热议问题