将公式应用于Excel中的多个工作表的多个列

时间:2017-03-22 19:17:38

标签: excel-vba excel-formula vba excel

我正在尝试将=LOWERCASE()公式应用于同一工作簿中多个工作表中的四列(J,O,T和Y)。

这是我到目前为止所使用的VBA代码,它适用于正确的列,但它为每个列返回错误。

Sub Clean_Lowercase()
Const N As Integer = 1
Dim r As Long, i As Integer, X As Integer, t As Long
Dim rng As Range, r As Range
Dim v As Variant
v = Array("J", "O", "T", "Y")
t = 1
For i = 1 To Sheets.Count - 1
r = Sheets(i).UsedRange.Rows.Count
For X = 0 To UBound(v)
    Set rng = Sheets(i).Range(v(X) & N & ":" & v(X) & r)
    For Each r In rng
        r.Formula = "=LOWERCASE()"
Next
Next
End Sub

我对VBA编码很新,任何建议都非常感谢!我真的很想学习。

非常感谢!

1 个答案:

答案 0 :(得分:0)

这有几个问题。

  1. 您正在使用r两次,一次是长,一次是一个范围。
  2. 缺少For Each循环Next
  3. 公式需要您想要设置为小写的参考。 例如,如果要使用左侧单元格的小写值,则应写入:=LOWERCASE(R[1]C[-1])
  4. 表单是一个基于1的集合,所以如果你写For i = 1 To Sheets.Count - 1,最后一页不会被处理(也许这是故意的?)并且代码将在第一张表中抛出错误(没有表(0)存在)
  5. 这样的工作:

    Sub Clean_Lowercase()
        Const N As Integer = 1
        Dim r As Long, i As Integer, X As Integer, t As Long
        Dim rng As Range, ri As Range
        Dim v As Variant
        v = Array("J", "O", "T", "Y")
        t = 1
        For i = 1 To Sheets.Count
            r = Sheets(i).UsedRange.Rows.Count
            For X = 0 To UBound(v)
                Set rng = Sheets(i).Range(v(X) & N & ":" & v(X) & r)
                For Each ri In rng
                    ri.Formula = "=LOWERCASE(R[1]C[-1])"
                Next
            Next
        Next
    End Sub