我正在尝试编写一些代码,该代码将在前30列和行中搜索单词Total
和Area
。我希望将这些单词的位置存储在一个变量中,然后使用这些变量清除相对于它们的范围,然后在所有工作表中循环。
我尝试使用在线找到的数字到字母转换器来存储列号,我认为这就是我要解决的问题。
这是我在网上找到的代码:
Function Col_Letter(lngCol As Long) As String
Dim vArr
vArr = Split(Cells(1, lngCol).Address(True, False), "$")
Col_Letter = vArr(0)
End Function
和我的代码:
Private Sub Clear_Click()
Dim LastRowH As Integer
Dim ClearContent As Boolean
Dim ws As Worksheet
Dim testrange As Range
Dim Cell1 As Range
Dim Celln As Range
ClearContent = False
For Each ws In ActiveWorkbook.Worksheets
'FINDS RANGE
For i = 1 To 30
For j = 1 To 30
If ActiveWorkbook.Sheets(ws).Range(Col_Letter(CLng(i)) & j).Value = "Total" Then
Cell1 = ws.Range(Col_Letter(CLng(i + 1)) & j)
End If
If ActiveWorkbook.Sheets(ws).Range(Col_Letter(CLng(i)) & j).Value = "Area" Then
Celln = ws.Range(Col_Letter(CLng(i + 1)) & j - 1)
End If
Next
Next
'...<more code here>...
If ClearContent = True Then
'...<more code here>...
ws.Range(Cell1 & ":" & Celln).ClearContents
End If
Next ws
End Sub
运行代码时,出现错误消息:
运行时错误'13':类型不匹配
我尝试了几种其他方法,但无法使其正常工作。
感谢您的帮助,在此先感谢:)
更新 我尝试替换代码中的for循环以使用“ Cells”函数,如下所示:
For i = 1 To 30
For j = 1 To 30
If Sheets(ws).Cells(j, i).Value = "Total" Then
Set Cell1 = ws.Cells(j - 1, i + 1)
End If
If Sheets(ws).Cells(j, i).Value = "Area" Then
Set Celln = ws.Cells(j, i + 1)
End If
Next
Next
但是我仍然收到类型不匹配
答案 0 :(得分:0)
您的类型不匹配是由于ActiveWorkbook.Sheets(ws).Range
而引起的,ws是工作表,而不是索引或名称。 ws.range
将扫描该工作表的范围。几乎没有其他修改,请参见注释。
Function Col_Letter(lngCol As Long) As String
Dim vArr
vArr = Split(Cells(1, lngCol).Address(True, False), "$")
Col_Letter = vArr(0)
End Function
Sub test()
Dim LastRowH As Integer
Dim ClearContent As Boolean
Dim ws As Worksheet
Dim testrange As Range
Dim Cell1 As Range
Dim Celln As Range
ClearContent = False
For Each ws In ActiveWorkbook.Worksheets
'FINDS RANGE
For i = 1 To 30
For j = 1 To 30
If ws.Range(Col_Letter(CLng(i)) & j).Value = "Total" Then
Set Cell1 = ws.Range(Col_Letter(CLng(i + 1)) & j) ' Set This
End If
If ws.Range(Col_Letter(CLng(i)) & j).Value = "Area" Then
Set Celln = ws.Range(Col_Letter(CLng(i + 1)) & j - 1) ' Set This
End If
Next
Next
'...<more code here>...
'ClearContent = True ' Me Testing
If ClearContent = True Then
'...<more code here>...
Cell1.ClearContents
Celln.ClearContents
'ws.Range(Cell1 & ":" & Celln).ClearContents ' don't think this will work properly
End If
Next ws
End Sub