我有一个数据库,其中所有数据都是大肆宣传,我只想保留这样的第一个字母,我的代码是
Sub nompropio()
Dim rng As Range
Dim cell As Range
Set rng = Range("A1:T17058")
For Each cell In rng
Next cell
If Not cell.HasFormula Then >>>here is the eror
End If
cell.Value = WorksheetFunction.Proper(cell.Value)
End Sub
我不知道是否有空白单元格是一个问题,或者是否有些列只是数字,但这些单元格中没有一个具有公式我只是把它放在一起,因为这个例子是那样的,我试图在没有那部分的情况下工作但是没有它奏效了。
答案 0 :(得分:0)
它应该使用以下语法:
Sub nompropio()
Dim rng As Range
Dim cell As Range
Set rng = Range("A1:T17058")
For Each cell In rng
If Not cell.HasFormula Then cell.Value = WorksheetFunction.Proper(cell.Value)
Next
End Sub
更新帖子
下面的版本使用变量数组和SpecialCells
运行相同的过程,比上面的范围循环版本快得多。
Sub Recut()
Dim X
Dim rng1 As Range
Dim rng2 As Range
Dim lngRow As Long
Dim lngCol As Long
On Error Resume Next
Set rng1 = Range("A1:T17058").SpecialCells(xlConstants)
On Error GoTo 0
If rng1 Is Nothing Then Exit Sub
For Each rng2 In rng1.Areas
If rng2.Cells.Count > 1 Then
X = rng2.Value2
For lngRow = 1 To UBound(X, 1)
For lngCol = 1 To UBound(X, 2)
X(lngRow, lngCol) = WorksheetFunction.Proper(X(lngRow, lngCol))
Next
Next
rng2.Value2 = X
Else
rng2.Value = WorksheetFunction.Proper(rng2.Value)
End If
Next
End Sub
答案 1 :(得分:0)
您指示的错误是因为变量超出范围。事实上,
在循环中,您可以隐式定义变量:
For Each cell In rng
Next cell
在每个循环中,您尝试调用变量:
If Not cell.HasFormula Then '>>>here is the error, because "cell" it's something within the previous loop, but it's nothing here so the compiler tells you "hey, I'm sorry, but I didn't set your variable".
End If
显然,变量超出范围,因为它在For Each
循环中定义,因此它仅存在于循环范围内。如果你想在没有公式的情况下在每个单元格上执行某些操作,那么这是正确的方法:
For Each cell In rng '<-- for each cell...
If Not cell.HasFormula Then '<-- perform if the cell has no formula
cell.Value = WorksheetFunction.Proper(cell.Value) '<--action to perform
End If '<-- end the if-then statement
Next cell '<-- go to the next cell of the range