VBA将公式设置为不同工作表中的多列

时间:2017-10-23 07:49:36

标签: excel vba excel-vba

我正在尝试修复不同列下的多个工作表中的日期,但我无法弄清楚如何使用。

Sub FixDate()
Dim i As Long

Sheets("Sheet1").Select

For i = 2 To Range("N" & Rows.Count).End(xlUp).Row
    With Range("N" & i)
        .NumberFormat = "mm/dd/yy hh:mm"
        .Value = DateValue(.Value)
    End With
Next i

For i = 2 To Range("O" & Rows.Count).End(xlUp).Row
    With Range("O" & i)
        .NumberFormat = "mm/dd/yy hh:mm"
        .Value = DateValue(.Value)
    End With

Next i


Sheets("Sheet2").Select

For i = 2 To Range("F" & Rows.Count).End(xlUp).Row
    With Range("F" & i)
        .NumberFormat = "mm/dd/yy hh:mm"
        .Value = DateValue(.Value)
    End With
Next i

End Sub

我有4个工作表需要修复不同列下的日期。请指教。

2 个答案:

答案 0 :(得分:1)

您可以将代码拆分为具有将所有单元格格式修改为"mm/dd/yy hh:mm"的Sub,然后多次调用它并传递相关列(作为String)和Worksheet对象。< / p>

注意:无需Select工作表即可修改其单元格格式。

<强>代码

Option Explicit

Sub FixDate()

' call sub, pass column "N" and worksheet object "Sheet1"
FixDatesInCol "N", ThisWorkbook.Worksheets("Sheet1")

FixDatesInCol "O", ThisWorkbook.Worksheets("Sheet1")

FixDatesInCol "F", ThisWorkbook.Worksheets("Sheet2")

End Sub
Sub FixDatesInCol(Col As String, ws As Worksheet)

Dim i As Long

With ws
    For i = 2 To .Range(Col & .Rows.Count).End(xlUp).Row
        With .Range(Col & i)
            .NumberFormat = "mm/dd/yy hh:mm"
            .Value = DateValue(.Value)
        End With
    Next i
End With

End Sub

答案 1 :(得分:0)

或者像这样:

Sub dates()
Dim sShts As String
Dim sCols As String
Dim i As Integer
Dim j As Integer

sCols = "N;O;F"
sShts = "1;1;2"

For j = 0 To UBound(Split(sShts, ";"))
    Debug.Print j
    With Worksheets("sheet" & Split(sShts, ";")(j))
        For i = 1 To .Range(Split(sCols, ";")(j) & Rows.Count).End(xlUp).Row
        With .Range(Split(sCols, ";")(j) & i)
            .NumberFormat = "mm/dd/yy hh:mm"
            .Value = DateValue(.Value)
        End With

    Next i
    End With
Next j
End Sub

只需编辑sCols和sShts即可调整/添加工作表/列。