如何在使用VBA时仅保护带有文本的单元格?

时间:2018-09-06 08:49:34

标签: excel vba

我知道如何使用以下方法保护工作表:-

List<Product> findByLocation(Location location){

        def criteria = ProductLocation.where {
            eq('location', location)

        }
        criteria.list()
    }



class Product {

        String title
        String imagepath
        String description
        Category category

        static belongsTo = [locations: Location]

        static mapping = {
            version false
        }

    static constraints = {
        title nullable: false
        imagepath nullable: false
        description nullable: true
    }

    static hasMany = [locations: Location]


}

class ProductLocation {

    Product product
    Location location


    static mapping = {
        version false
    }

    static constraints = {

    }

    static belongsTo = [products: Product, locations: Location]


}

class Location  {

    Company customer
    Location parent
    String name
    String description
    String objectnumber
    String address
    String zipcode
    String province
    String city
    String country
    Long longitude
    Long latitude
    Integer order
    String timezone
    AlertConfiguration alertConfiguration
    boolean deleted
    LocationType type


    static hasMany = [products: Product]

    static mapping = {

    }


}

我只想保护有文本的单元格。我的问题是列数各不相同。如何计算列并仅保护其中包含文本的单元格?

2 个答案:

答案 0 :(得分:1)

您可以只检查所有单元格并锁定是否有文字:

Dim Cell As Range
For Each Cell in Sheet1.UsedRange
    If Cell.Value <> "" Then Cell.Locked = True
Next Cell

答案 1 :(得分:1)

以下内容将达到您的期望:

Sub protectit()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set the worksheet you are working with, amend as required
Dim c As Range
ws.Cells.Locked = False 'unlock all the cells in the given Sheet
For Each c In ws.UsedRange 'for each cell in UsedRange
    If c.Value <> "" Then c.Locked = True 'if cell is not empty then locked = True
Next
ws.protect Password:="erty", UserInterfaceOnly:=True 'protect the populated cells
End Sub