Vba代码:动态填充零空白单元格

时间:2016-02-03 05:40:53

标签: excel-vba vba excel

我需要在零工作表中填充空白单元格。目前我正在为C12:H35做这件事。有人可以告诉我的代码有什么问题。它甚至没有给出任何错误。我还需要动态地做。所以我试着做

Dim sht as Worksheet Set sht = This Workbook.Sheets("MySheet") sht.Range(sht.cells(C12:3),sht.cells(12,Columns.count).End(xlToLeft)).Select

没有工作:(

此代码适用于非动态范围,但无效

  Sub FillEmptyCell
      Dim rng as Range
      Dim i as Long
      Dim cell as Range
  Set rng= Sheets("Mysheet").Range("C12:H35")

For each cell in rng
  If cell.value = " " Then cell.value= "0"
  End if 
Next
End Sub

4 个答案:

答案 0 :(得分:0)

我还有一个建议给你。

  Sub FillEmptyCell()
  Dim rng as Range
  Dim i as Long
  Dim cell as Range
  Set rng= Sheets("Mysheet").Range("C12:H35")
  Sheets("Mysheet").Activate
  rng.Select
  Selection.Replace What:="", Replacement:="0", LookAt:=xlWhole, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

  End Sub

答案 1 :(得分:0)

本规范对我有用

Sub FillEmptyCell()
  Dim rng As Range
  Dim i As Long
  Dim cell As Range
  Dim sht As Worksheet
  Set sht = ActiveWorkbook.Sheets("Sheet1")
  sht.Activate
  'Range("C12:AL12").Select
  'Range(Selection, Selection.End(xlDown)).Select
  Set rng = Range(Range("C12"), Range("AD" & sht.UsedRange.Rows.Count))
  For Each cell In rng
    If cell.Value = "" Then cell.Value = "0"
  Next
End Sub

答案 2 :(得分:0)

您的代码没问题,但是if语句已关闭,我还更改了引号,使其中没有空格。在这种情况下,VBA会在单元格中查找空格,而不是空单元格。

Sub FillEmptyCell()
Dim rng As Range
Dim i As Long
Dim cell As Range

    Range("C1").Select
    colRef = ActiveCell.Column
    lastrow = Cells(Rows.Count & colRef).End(xlUp).Row
    Do Until ActiveCell.Column = 31
        colRef = ActiveCell.Column
        lastrow = Cells(Rows.Count & colRef).End(xlUp).Row
        For x = 1 To lastrow
            If ActiveCell.Value = "" Then
                ActiveCell.Value = "0"
                ActiveCell.Offset(1).Select
            Else
                ActiveCell.Offset(1).Select
            End If
        Next
        ActiveCell.Offset(-lastrow, 1).Select
    Loop
End Sub

答案 3 :(得分:0)

在工作表中选择一个范围,然后尝试运行此代码

Sub FillBlanksWithZero()
    Dim rng As Range

    Set rng = Range(Selection.Address)
    Selection.SpecialCells(xlCellTypeBlanks).Select
    Selection.FormulaR1C1 = "0"
End Sub

我希望这会对您有所帮助:)