【问题标题】:Move cells in column automatically up when delete first cells删除第一个单元格时自动向上移动列中的单元格
【发布时间】:2019-08-05 13:58:36
【问题描述】:

我在 Excel 工作表中自动移动一列(6000 行)。它只有值 1 或 0。我希望 excel 自动看到列中的第一个 1,然后删除该行上方包含值 1 的所有内容。当第一个 1 上方被删除时,我想将所有内容向上移动。

我尝试使用一些代码,但我只能检测到包含第一个 1 的第一行。我希望有人可以帮助我开发一些代码。

我找到了一些代码来查找列中的第一个值 1。

谢谢, 米切尔·戈默斯

Sub Macro1()

Dim intMyVal As Integer
Dim lngLastRow As Long
Dim strRowNoList As String

intMyVal = 1 'Value to search for, change as required.
lngLastRow = Cells(Rows.Count, "A").End(xlUp).Row 'Search Column A, change as required.

For Each cell In Range("A2:A" & lngLastRow) 'Starting cell is A2, change as required.

    If cell.Value = intMyVal Then
        If strRowNoList = "" Then
        strRowNoList = strRowNoList & cell.Row
        Else
        strRowNoList = strRowNoList & ", " & cell.Row
        End If
    End If
Next cell

End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    您可以使用Range("--").Delete xlShiftUp 将单元格向上移动。你的情况

    Sub Macro1()
    
    Dim intMyVal As Integer
    Dim lngLastRow As Long
    Dim strRowNoList As String
    
    intMyVal = 1 'Value to search for, change as required.
    lngLastRow = Cells(Rows.Count, "A").End(xlUp).row 'Search Column A, change as required.
    
    For Each cell In Range("A2:A" & lngLastRow) 'Starting cell is A2, change as required.
    
        If cell.Value = intMyVal Then
    
            Range("A2:A" & cell.row - 1).Delete xlShiftUp
            Exit For
    
        End If
    Next cell
    
    End Sub
    

    这将删除 A 列中第一个 1 之上的所有内容。

    【讨论】:

      【解决方案2】:

      这是另一种不使用循环的方法。

      Option Explicit
      
      Sub Sample()
          Dim ws As Worksheet
          Dim rw As Long
      
          Set ws = Sheet1
      
          With ws
              On Error Resume Next
              rw = Application.Evaluate("=MATCH(1,A:A,0)")
              On Error GoTo 0
      
              If rw < 3 Then Exit Sub
      
              .Rows("2:" & rw-1).Delete
          End With
      End Sub
      

      【讨论】:

      • 我认为你需要使用精确匹配。
      • 为了更安全,我添加了它:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多