簡體   English   中英

Excel VBA宏:找到列中的第一個空單元格並自動填充它

[英]Excel VBA macro: Locating first empty cell in a column and automatically filling it

我在電子表格中有兩列,列(A)和列(B)。

列(A)包含從查詢中提取的名稱(例如Brian,Bob,Bill等),列(B)包含三種狀態之一(已分配,正在進行或待定)。

但是,此查詢有時會為沒有名稱的狀態提取顯示“已分配”的某些行項目,因此表示列(A)中名稱的相應單元格為空。 所以我用“未知”手動填寫那些空單元格。

我想要做的是創建一個宏,找到列(A)中的每個空單元格,如果右邊的單元格包含單詞“Assinged”,則填寫單詞“Unknown”。

所以條件是:

  1. 專欄(A)中的空白單元格

  2. 右側的Correspoding單元格(B列)包含“assinged”一詞

這是我的代碼:

Private Sub CommandButton2_Click()

    For Each cell In Columns("A")
        If ActiveCell.Value = Empty And ActiveCell.Offset(0, 1).Value = "Assigned" Then ActiveCell.Value = "Unknown"
    Next cell

End Sub   

沒有必要在這里循環,利用excels內置的方法,將更快地執行。

Private Sub CommandButton2_Click()

    Application.ScreenUpdating = False

    With ActiveSheet.UsedRange
        .AutoFilter Field:=1, Criteria1:=""
        .AutoFilter Field:=2, Criteria1:="Assigned"

        If WorksheetFunction.CountBlank(.Columns(1)) > 0 Then
            If .Columns(1).SpecialCells(xlCellTypeVisible).Count > 1 Then
                .Columns(1).SpecialCells(xlCellTypeBlanks).Value = "Unknown"
            End If
        End If

        .AutoFilter
    End With

    Application.ScreenUpdating = True

End Sub

歡迎來到SO。

試試這個代碼。 它會更快一點,應該得到你想要的。

更新 :使代碼更加防彈!

Private Sub CommandButton2_Click()

Dim cel As Range, rngFind As Range, rngFilter As Range
Dim wks As Worksheet

Set wks = Sheets("sheet1")

With wks

    '-> Error check to make sure "blanks" exist
    Set rngFind = .Range("A1:A" & .Range("B" & Rows.Count).End(xlUp).Row).Find("", lookat:=xlWhole)

    If Not rngFind Is Nothing Then

        Set rngFilter = .Range("A1:B" & .Range("B" & Rows.Count).End(xlUp).Row)

        rngFilter.AutoFilter 1, "="

        '-> Error check to make sure "assigned" exists for blank cells
        Set rngFind = .Columns("B:B").SpecialCells(xlCellTypeVisible).Find("Assigned", lookat:=xlWhole)

        If Not rngFind Is Nothing Then
        '-> okay, it exists. filter and loop through cells

            rngFilter.AutoFilter 2, "Assigned"

            Set rngFind = Intersect(.UsedRange, .UsedRange.Offset(1), .Columns(1)).SpecialCells(xlCellTypeVisible)

            For Each cel In rngFind

                If cel.Offset(0, 1).Value = "Assigned" Then cel.Value = "Unknown"

            Next cel

        End If

    End If

End With


End Sub

如果你只需要這樣做幾次就可以了

  1. 將您使用的范圍格式化為表格
  2. 在列A過濾器上只顯示“(空白)”
  3. 在B列過濾器上只顯示“assinged”
  4. 選擇B列中的所有結果單元格
  5. alt + 僅選擇可見單元格
  6. F2
  7. 輸入“未知”
  8. ctrl + enter

你的壞數據現在應該是好的!

顯然這是一個非基於vba的解決方案,但如果你可以避免編碼,它可能是最好的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM