Clear contents of cells in VBA using column reference

后端 未结 8 1891
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 22:31

I am trying to get a piece of code to clear the data in some cells, using the column references. I am using the following code:

Worksheets(sheetname).Range(.         


        
8条回答
  •  执念已碎
    2021-01-01 23:22

    As Gary's Student mentioned, you would need to remove the dot before Cells to make the code work as you originally wrote it. I can't be sure, since you only included the one line of code, but the error you got when you deleted the dots might have something to do with how you defined your variables.

    I ran your line of code with the variables defined as integers and it worked:

    Sub TestClearLastColumn()
    
        Dim LastColData As Long
            Set LastColData = Range("A1").End(xlToRight).Column
    
        Dim LastRowData As Long
            Set LastRowData = Range("A1").End(xlDown).Row
    
        Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).ClearContents
    
    End Sub
    

    I don't think a With statement is appropriate to the line of code you shared, but if you were to use one, the With would be at the start of the line that defines the object you are manipulating. Here is your code rewritten using an unnecessary With statement:

    With Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData))
        .ClearContents
    End With
    

    With statements are designed to save you from retyping code and to make your coding easier to read. It becomes useful and appropriate if you do more than one thing with an object. For example, if you wanted to also turn the column red and add a thick black border, you might use a With statement like this:

    With Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData))
        .ClearContents
        .Interior.Color = vbRed
        .BorderAround Color:=vbBlack, Weight:=xlThick
    End With
    

    Otherwise you would have to declare the range for each action or property, like this:

        Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).ClearContents
        Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).Interior.Color = vbRed
        Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).BorderAround Color:=vbBlack, Weight:=xlThick
    

    I hope this gives you a sense for why Gary's Student believed the compiler might be expecting a With (even though it was inappropriate) and how and when a With can be useful in your code.

提交回复
热议问题