W2 寫入公式=(V2/天數)/(U2/天數),如果V和U所在列的月份如果是1.3.5.7.8.10.12月則除31,如果是2.4.6.9.11則除30,如何用VBA表達
时间: 2024-04-14 16:29:16 浏览: 20
您可以使用以下的 VBA 代码来实现您所描述的公式:
```vba
Sub CalculateW2()
Dim lastRow As Long
Dim ws As Worksheet
Dim vCol As Long, uCol As Long, wCol As Long
Dim i As Long
Set ws = ThisWorkbook.Worksheets("Sheet1") '将 "Sheet1" 替换为实际的工作表名称
lastRow = ws.Cells(ws.Rows.Count, "V").End(xlUp).Row '假设 V 列是 V 的列号,U 列是 U 的列号,W 列是 W 的列号
vCol = Columns("V").Column '将 "V" 替换为实际的 V 列字母
uCol = Columns("U").Column '将 "U" 替换为实际的 U 列字母
wCol = Columns("W").Column '将 "W" 替换为实际的 W 列字母
For i = 2 To lastRow '假设数据从第二行开始,如果是从第一行开始,请将 "2" 替换为 "1"
Dim vValue As Double, uValue As Double, wValue As Double
vValue = ws.Cells(i, vCol).Value
uValue = ws.Cells(i, uCol).Value
Dim days As Integer
Dim month As Integer
month = Month(ws.Cells(i, vCol).Value) '假设月份在 V 列中,如果在 U 列中,请将 "vCol" 替换为 "uCol"
Select Case month
Case 1, 3, 5, 7, 8, 10, 12
days = 31
Case 2, 4, 6, 9, 11
days = 30
End Select
wValue = (vValue / days) / (uValue / days)
ws.Cells(i, wCol).Value = wValue
Next i
End Sub
```
请注意,上述代码假设数据从第二行开始,如果数据从第一行开始,请将 `For` 循环中的起始行数从 `2` 改为 `1`。另外,代码中假设月份在 V 列中,如果月份在 U 列中,请将 `month = Month(ws.Cells(i, vCol).Value)` 中的 `vCol` 替换为 `uCol`。最后,代码还假设 V、U 和 W 列分别是 V、U 和 W 的列号,如果不是,请相应地更改这些变量的赋值。
您可以将代码复制粘贴到 VBA 编辑器中,并在需要的时候运行它。请确保将 "Sheet1" 替换为实际的工作表名称,并根据实际情况调整代码中的其他部分。