找回密码
 注册

QQ登录

只需一步,快速开始

查看: 758|回复: 1

Excel VBA -- Fill Blank Cells in Excel Column

[复制链接]
发表于 2012-8-24 10:41:25 | 显示全部楼层 |阅读模式
本帖最后由 demo 于 2012-8-25 03:17 编辑

Fill Blank Cells Manually        
        Some worksheets contain cells that have been left blank, in order to make the headings and subheadings easier to read.
        However, if you want to sort or filter the list, you need to fill in the blanks, by copying the value from the first filled cell above the blank.
        The following technique makes it easy to fill in the blanks.





          Start by selecting the empty cells:
        
  • Select the cells in the column, starting in the row below the column heading.
  • Choose Edit | Go To
  • Click the Special button
  • Select Blanks, click OK
      


        
         
          Enter the formula to copy the value:
               
  • Type an equal sign
  • Press the up arrow on the keyboard -- this will enter a reference to the cell above -- cell A2 in this example
  • Hold the Ctrl key and press Enter -- this enters the formula in all selected cells
      


         
          Change the formulas to values:
        In order to sort or filter the data, the formulas must be changed to           values.
        
  • Select the entire column
  • Choose Edit | Copy
  • With the column still selected, choose Edit | Paste Special
  • Select Values, click OK
        Note: Do this carefully if there are other cells in the range           which contain formulas.
               


         
        
      
         
Fill Blank Cells Programmatically


        If you frequently have to fill blank cells, you may prefer to use a macro. The following code examples will fill blank cells in the active column. Each example uses a different method to find the last row, and to fill the blank cells.
        For more information on finding the last row, see Ron de Bruin's page:  Find last row, column or last cell. Ron explains the advantages and disadvantages of each method.
        
Fill Blank Cells Macro - Example 1

        The first example, from Dave Peterson, uses a formula to fill the cells, and pastes the results as values. The code uses the .SpecialCells(xlCellTypeLastCell) method to find the last row.
  1. Sub FillColBlanks()
  2. 'by Dave Peterson  2004-01-06
  3. 'fill blank cells in column with value above
  4. 'http://www.contextures.com/xlDataEntry02.html
  5. Dim wks As Worksheet
  6. Dim rng As Range
  7. Dim LastRow As Long
  8. Dim col As Long

  9. Set wks = ActiveSheet
  10. With wks
  11.    col = activecell.column
  12.    'or
  13.    'col = .range("b1").column

  14.    Set rng = .UsedRange  'try to reset the lastcell
  15.    LastRow = .Cells.SpecialCells(xlCellTypeLastCell).Row
  16.    Set rng = Nothing
  17.    On Error Resume Next
  18.    Set rng = .Range(.Cells(2, col), .Cells(LastRow, col)) _
  19.                   .Cells.SpecialCells(xlCellTypeBlanks)
  20.    On Error GoTo 0

  21.    If rng Is Nothing Then
  22.        MsgBox "No blanks found"
  23.        Exit Sub
  24.    Else
  25.        rng.FormulaR1C1 = "=R[-1]C"
  26.    End If

  27.    'replace formulas with values
  28.    With .Cells(1, col).EntireColumn
  29.        .Value = .Value
  30.    End With

  31. End With

  32. End Sub
复制代码

                       



         Fill Blank Cells Macro - Example 2

        In the following code, Rick Rothstein uses the .Find method to calculate the last row. Instead of using a formula to fill from above, each cell gets its value from the cell above the first cell of the Area that it's in, using the Offset property.
  1. Sub FillColBlanks_Offset()
  2. 'by Rick Rothstein  2009-10-24
  3. 'fill blank cells in column with value above
  4. 'http://www.contextures.com/xlDataEntry02.html

  5.   Dim Area As Range, LastRow As Long
  6.   On Error Resume Next
  7.   LastRow = Cells.Find(What:="*", SearchOrder:=xlRows, _
  8.                SearchDirection:=xlPrevious, _
  9.                LookIn:=xlFormulas).Row
  10.   For Each Area In ActiveCell.EntireColumn(1).Resize(LastRow). _
  11.                SpecialCells(xlCellTypeBlanks).Areas
  12.     Area.Value = Area(1).Offset(-1).Value
  13.   Next
  14. End Sub
复制代码





         Fill Blank Cells Macro - Example 3
        This example combines Dave Peterson's code (Example 1), with the special cells test from Ron de Bruin.
        In Excel 2007, and earlier versions, there is a problem with special cells if there are more than 8192 different areas in the special cells range. This problem has been fixed in Excel 2010.
        This code tries to count the areas, and if over the limit, it loops through the range in groups of 8000 rows.
  1. Sub FillColBlanks()
  2. 'http://www.contextures.com/xlDataEntry02.html
  3. 'by Dave Peterson  2004-01-06
  4. 'fill blank cells in column with value above

  5. '2010-10-12 incorporated Ron de Bruin's test for special cells limit
  6. 'http://www.rondebruin.nl/specialcells.htm

  7. Dim wks As Worksheet
  8. Dim rng As Range
  9. Dim rng2 As Range
  10. Dim LastRow As Long
  11. Dim col As Long
  12. Dim lRows As Long
  13. Dim lLimit As Long

  14. Dim lCount As Long
  15. On Error Resume Next

  16. lRows = 2 'starting row
  17. lLimit = 8000

  18. Set wks = ActiveSheet
  19. With wks
  20.    col = ActiveCell.Column

  21.    Set rng = .UsedRange  'try to reset the lastcell
  22.    LastRow = .Cells.SpecialCells(xlCellTypeLastCell).Row
  23.    Set rng = Nothing
  24.    
  25.     lCount = .Columns(col).SpecialCells(xlCellTypeBlanks).Areas(1).Cells.Count
  26.    
  27.     If lCount = 0 Then
  28.         MsgBox "No blanks found in selected column"
  29.         Exit Sub
  30.     ElseIf lCount = .Columns(col).Cells.Count Then
  31.         MsgBox "Over the Special Cells Limit" 'this line can be deleted
  32.         Do While lRows < LastRow
  33.             Set rng = .Range(.Cells(lRows, col), .Cells(lRows + lLimit, col)) _
  34.                            .Cells.SpecialCells(xlCellTypeBlanks)
  35.             rng.FormulaR1C1 = "=R[-1]C"
  36.             lRows = lRows + lLimit
  37.         Loop
  38.     Else
  39.         Set rng = .Range(.Cells(2, col), .Cells(LastRow, col)) _
  40.                        .Cells.SpecialCells(xlCellTypeBlanks)
  41.         rng.FormulaR1C1 = "=R[-1]C"
  42.     End If

  43.    'replace formulas with values
  44.    With .Cells(1, col).EntireColumn
  45.        .Value = .Value
  46.    End With

  47. End With

  48. End Sub
复制代码

http://www.contextures.com/xlDataEntry02.html
 楼主| 发表于 2012-8-27 12:51:01 | 显示全部楼层

Excel VBA -- Fill Blank Cells in Excel Column

本帖最后由 demo 于 2012-8-28 05:04 编辑

This is my total code to do this, including open file and save the Excel file in a new file name.


'Description: There is a grouped Excel sheet. we need to fill all the empty cells under customer name with the real name listed at the top cell, and, after finish it, save it to a new Excel file. with file name distinctive to the originals.

Sub BlankProcess()
    'Code by: John Zhang
    'Date: August 27, 2012
    Dim strFile As String, repcode As Integer
    Dim myList, myCell, myGet, i
    i = 1
   
    repcode = 0
    With Application
        .DefaultFilePath = "\\sales-server\e$\InvShare\SpecialItems"
        'ChDrive ("\\sales-server")
        ChDir ("\\sales-server\e$\InvShare\SpecialItems")
        strFile = .GetOpenFilename("Excel files (*.xls), *.xls*," & _
                                          "CSV files (*.csv)  , *.csv," & _
                                          "All files (*.*)    , *.*", 1, "Open Item File", "", False)
    End With
    If strFile <> "False" Then
       Workbooks.Open strFile
       If Len(strFile) > 1 Then
          repcode = MsgBox("You openned file " & strFile & ".", vbOKOnly, "Notice")
       Else
          MsgBox "Nothing to be done with empty command."
       End If
       'strFile =
       If ActiveSheet.Parent.FullName = strFile Then
           MsgBox "Data processed here ..."
       End If
       'ActiveSheet.Range("D9 : D65530").Select
       'myList = ActiveSheet.Range("D9 : D65535").Select
       ActiveSheet.Range("D9 : D65535").Select
       myGet = Empty
       i = 0
       For Each myCell In Selection
           'myCell.Value = "i"
           'Windows("PERSONAL").Activate
           If myCell.Column = 4 Then 'Because we have merged cells, so we just need to check the specific column every row
           If myCell = Empty Then
              If myCell.Offset(0, 2) = Empty Then
                 Save_As ""
                 Exit Sub ' to make sure it stops when table ended.
              End If
              i = i + 1
              myCell.Value = myGet
           Else
              myGet = myCell.Value
              i = 0
           End If
           'Sheets("Sheet1").Cells(i, 1).Value = myCell.Value
           'Windows("Book1").Activate
           i = i + 1
           End If
       Next
       ActiveSheet.Select
    Else: Exit Sub
    End If
    ChDrive (Left(Application.DefaultFilePath, 1))
    ChDir (Application.DefaultFilePath)

End Sub

Sub Save_As(strName As String)
' sub program
' Name: Save_As
'strName -- the file name to be saved as

'
    'Code by: John Zhang
    'Date: August 27, 2012
    Dim xFile, strNewFile, strFileName As String
    Dim cnt1, cnt2 As Integer
    xFile = strNewFile = strFileName = ""
    If strName = Empty Then
       strName = ActiveWorkbook.FullName
    End If
    cnt1 = InStr(1, strName, ".", vbTextCompare)
    If cnt1 > 0 Then
       xFile = Right(strName, Len(strName) - cnt1)
       strFileName = Left(strName, cnt1 - 1)
    Else
       strFileName = strName
    End If
    strNewFile = strFileName & "(Name Filled)." & xFile
    MsgBox "Active sheet is """ & ActiveSheet.Name & """ in " & vbCrLf & _
       ActiveWorkbook.FullName
    ActiveWorkbook.SaveAs Filename:= _
        strNewFile _
        , FileFormat:=xlExcel8, Password:="", WriteResPassword:="", _
        ReadOnlyRecommended:=False, CreateBackup:=False
End Sub

您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )

GMT-8, 2026-6-11 13:59 , Processed in 0.021096 second(s), 15 queries .

Supported by Weloment Group X3.5

© 2008-2026 Best Deal Online

快速回复 返回顶部 返回列表