Access VBA to split out ALL merged cell in Excel

情到浓时终转凉″ 提交于 2019-12-08 08:36:44

问题


I need to import some Excel files into Access database. I know how to write the import function in VBA but it is not working as I expected since some merged cell in Excel cause me trouble.

So for example, in the Excel spreadsheet

When importing to Access table, it imported row by row . So the 1st row should be 1-pencil-90, and it is correct but the 2nd and 3rd row is empty due to the merged cell. The result is

No|Product|Storage
1 | pencil|90
  |       |23
  |       |41

But expected result should be:

No|Product|Storage
1 | pencil|90
1 | pencil|23
1 | pencil|41

I want the VBA to split the merged cells and also fill in the blank data with the information in the merged cell. Please keep in mind that I got a lot of merged cells and manually change is impossible. I am open to any solution that help me achieve the desire result.

P/S: The aata can be left blank so I can't use conditional check if it blank then look up the above data.


回答1:


Try this

Sub UnMergeRanges()
    Dim cl As Range
    Dim rMerged As Range
    Dim v As Variant

    For Each cl In ActiveSheet.UsedRange
        If cl.MergeCells Then
            Set rMerged = cl.MergeArea
            v = rMerged.Cells(1, 1)
            rMerged.MergeCells = False
            rMerged = v
        End If
    Next
End Sub

How it works:

  • Loop through cells in the used range
  • If the cell is part of a merged range
    • Set a Range variable to the Merged Range
    • Record the current value of the Top Left cell in the range into a variable v. This is the value the merged range displays
    • Unmerge the range
    • write the recorded value (v) into all cells of the now unmerged range


来源:https://stackoverflow.com/questions/17720395/access-vba-to-split-out-all-merged-cell-in-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!