简体   繁体   中英

Range Column and add Value to the specific range

I have Excel file that I want to filter about one column and on another column add specific value

Excel文件

Sub Macro1()
'
' Macro1
'

'
    Range("Table1[type phone]").Select
    ActiveSheet.ListObjects("Table1").Range.AutoFilter Field:=1, Criteria1:= _
        "=*samsung*", Operator:=xlAnd
        Range("Table1[company]").Select

        'Here I want to  add the specific value "Samsung"'

    ActiveSheet.ListObjects("Table1").Range.AutoFilter Field:=1, Criteria1:= _
        "=*iphone*", Operator:=xlAnd
        Range("Table1[company]").Select

        'Here I want to  add the specific value "Apple"'

End Sub

Also how can I filter about one column Blanks cells and on another column add specific value "other"?

[ 其他项目[2]

What conditions can be written if, for example, the Samsung Devices table is missing? Because if I run the code it crashes in the line it is looking for Samsung.

没有三星设备

How can I do it? Thank You for helping!

To change the value of only cells that are visible (aka those that are show in the filter) you can use SpecialCells(xlCellTypeVisible)

So for your example the code that would go in the first break would be

"Range("B2:B18").SpecialCells(xlCellTypeVisible).Value= "Samsung"

and the second break

"Range("B2:B18").SpecialCells(xlCellTypeVisible).Value= "Apple"

You need to change "18" to whatever the last row is. (Or you can define a variable called LastRow and then call that instead of hard-coding the number which means it will dynamically change based on how many rows there are.)


With LastRow

Sub Macro1()

 Dim LastRow As Long
  LastRow = ActiveSheet.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row

    Range("Table1[type phone]").Select
    ActiveSheet.ListObjects("Table1").Range.AutoFilter Field:=1, Criteria1:= _
        "=*samsung*", Operator:=xlAnd
        Range("Table1[company]").Select

Range("B2:B" & LastRow).SpecialCells(xlCellTypeVisible).Value= "Samsung"

    ActiveSheet.ListObjects("Table1").Range.AutoFilter Field:=1, Criteria1:= _
        "=*iphone*", Operator:=xlAnd
        Range("Table1[company]").Select

Range("B2:B" & LastRow).SpecialCells(xlCellTypeVisible).Value= "Apple"
End Sub

We created a new variable called LastRow and defined it as long (A type of number). Then we defined LastRow according to a formula I use from this site: https://www.thespreadsheetguru.com/blog/2014/7/7/5-different-ways-to-find-the-last-row-or-last-column-using-vba

Finally we replace Range("B2:B18") with Range("B2:B" & LastRow) which dynamically replaces the 18 with the number LastRow.

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