请注意,我是VBA的新手
我有很多列。如果任何列的标题为“ X”,我希望它清除该列中的10-20行。我知道我必须创建一个函数,但是我无法弄清楚该函数是什么。功能和循环在下面供您查看。
感谢您的帮助
Public Function ColumnLettersFromRange(rInput As Range) As String
ColumnLettersFromRange = Mid(ActiveCell.Address, 2, InStrRev(ActiveCell.Address, "$") - 2)
End Function
dim RowDelete
Set RowDelete = Range("A9:Z9")
For Each cell in RowDelete
if cell.value = "X" then (ColumnLettersFromRange & "10:" &
ColumnLettersFromRange & 20).clear
Next Cell
答案 0 :(得分:1)
我认为这可以完成您想做的事(无需创建函数)
Sub test1()
Dim RowDelete As Range, cell As Range
Set RowDelete = Range("A9:Z9")
For Each cell In RowDelete
If cell.Value = "X" Then Range(cell.Offset(1, 0), cell.Offset(11, 0)).Clear
Next cell
End Sub
如果您想使用功能并坚持使用您的代码,请尝试(您的代码已修改为可以使用)。您尚未向函数提供参数rInput
,并用Range(...)
包含了结果字符串。
Public Function ColumnLettersFromRange(rInput As Range) As String
ColumnLettersFromRange = Mid(rInput.Address, 2, InStrRev(rInput.Address, "$") - 2)
End Function
Sub test2()
Dim RowDelete as Range, cell As Range
Set RowDelete = Range("A9:Z9")
For Each cell In RowDelete
If cell.Value = "X" Then Range(ColumnLettersFromRange(cell) & "10:" & ColumnLettersFromRange(cell) & 20).Clear
Next cell
End Sub
答案 1 :(得分:0)
您可以尝试:
代码:
Option Explicit
Sub test()
Dim LastColumn As Long, i As Long
With ThisWorkbook.Worksheets("Sheet1")
'Let us assumne that headers appear in row number 1. Find the last column of row number 1
LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
For i = 1 To LastColumn
If .Cells(1, i).Value = "Clear" Then
.Range(.Cells(10, i), .Cells(20, i)).ClearContents
End If
Next i
End With
End Sub
结果:
注意:
.Clear
清除值和格式.ClearContents
仅清除值