【问题标题】:Autofill a specific text in a range in excel 2013在excel 2013中自动填充范围内的特定文本
【发布时间】:2017-06-25 17:58:48
【问题描述】:

我正在尝试通过 vba 在 excel 2013 中自动填充范围(N6:N125)中的文本。当范围引用单个单元格而不是范围时,我的代码工作正常。你能帮我找出我的错误吗?我的代码是

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Range("N6:N125") = "" Then
Range("N6:N125").value = "My Text"
End If
End Sub

【问题讨论】:

    标签: excel text autofill vba


    【解决方案1】:

    如果您只想填充 N6N125 中的空单元格,并且某些单元格可能已经有值,但没有一个有公式,那么循环不是实际需要:

    Sub marine()
        Dim r As Range, s As String
        Set r = Range("N6:N125")
        s = "=IF(N6:N125="""",""MyText"",N6:N125)"
        r.Value = Evaluate(s)
    End Sub
    

    【讨论】:

      【解决方案2】:
      If Range("N6:N125") = "" Then
      

      这不起作用。您将需要逐个单元地进行此测试。一个更简单的选择是:

      Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        On Error Resume Next
        Range("N6:N125").SpecialCells(xlCellTypeBlanks).value = "My Text"
      End Sub
      

      这将填充范围内的空白单元格。但是,如果您的测试目的是检查整个范围是否为空,则:

      Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        If Application.CountA(Range("N6:N125")) = 0 Then Range("N6:N125").value = "My Text"
      End Sub
      

      【讨论】:

        【解决方案3】:

        你可以使用:

        Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        
        
        With Selection
        
        For Each cell In Selection
        
        If cell = "" Then
        cell.Value = "My Text"
        End If
        Next cell
        End With
        End Sub 
        

        此代码将测试您选择的每个单元格是否为空并在其中写入“我的文本”,但如果它不为空,它将跳过它。

        在您的代码中,您没有测试每个单元格,也没有使用循环从一个单元格移动到另一个单元格

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-08-09
          • 1970-01-01
          • 1970-01-01
          • 2018-07-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多