简体   繁体   中英

how to replace text after autofilter has been applied

I can't figure it out how to replace the value of a range after apply autofilter

my code below

Dim ws1 As Worksheet
Dim myname As String
Dim LastRow As Double
Dim LastRow2 As Double

 myname = "Inventory"
 Set ws1 = Sheets(myname)
 ws1.Activate
 ws1.Cells(1, 1).Select


  '  Find the last row
   LastRow = ws1.Range("A1").CurrentRegion.Rows.Count

  'select the table we are gonna work with
   ws1.Range("A1:Q" & LastRow).Select

  'filter table
   Selection.AutoFilter Field:=6, Criteria1:="Online"

  'Find the last row
   LastRow2 = ws1.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 1


   ' I want to select only the visible rows from column H after auto filter
    'h1 is header cell
   ActiveSheet.Range("H2:H" & LastRow).SpecialCells(xlCellTypeVisible).Select

   Selection.Copy ' to remove formulas

   Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False


    Range("H1:H" & 
    LastRow).SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeBlanks).Value ="My new 
    text here"

the above code errors out, it says cant find the cells

Any ideas how I can do it?

Fill Empty Cells of a Filtered Column

在此处输入图像描述

Sub Test()

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    Dim ws As Worksheet: Set ws = wb.Sheets("Inventory")
    If ws.FilterMode Then ws.ShowAllData
    
    Dim trg As Range: Set trg = ws.Range("A1").CurrentRegion ' has headers
    Dim drg As Range
    Set drg = trg.Resize(trg.Rows.Count - 1).Offset(1).Columns("H") ' no headers
    
    trg.AutoFilter 6, "Online"
    
    ' Reference the visible cells of the single-column Data range (no headers),
    ' the Visible range.
    Dim dvrg As Range
    On Error Resume Next
        Set dvrg = drg.SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
    
    ws.AutoFilterMode = False
    
    If dvrg Is Nothing Then
        MsgBox "No visible cells in column.", vbExclamation
        Exit Sub
    End If
    
    ' Convert to values.
    
    Dim arg As Range
    
    For Each arg In dvrg.Areas
        arg.Value = arg.Value
    Next arg
    
    ' Reference the empty cells of the Visible range, the Empty range.
    
    Dim derg As Range
    On Error Resume Next
        Set derg = dvrg.SpecialCells(xlCellTypeBlanks)
    On Error GoTo 0
    
    If derg Is Nothing Then
        MsgBox "No empty cells in visible cells of column.", vbExclamation
        Exit Sub
    End If
    
    derg.Value = "My new text here"
    
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM