范围乘以当月剩余天数的百分比

时间:2018-10-05 13:58:43

标签: excel vba excel-vba

我在写这段代码的最后一部分时遇到了麻烦。

我试图让excel根据今天来计算当前月份剩余天数的百分比。然后,它将一个单元格范围乘以该值。

当它实际相乘时,所有单元格都变为“ #NAME”。我检查了msgbox,它的计算部分正确进行了(找到正确的百分比),但是当插入最后一个要相乘的公式时,它不起作用。

当我从公式中取出变量并放入实际数字时,它可以正常工作。我认为将变量写入最终序列的方式有问题。我的格式有什么问题?

Sub MultiplyDayRatio()

Dim rngData As Range
Dim MyDate As Date
Dim DaysLeft As Integer
Dim DaysInMonth As Integer
Dim PercentLeft As Double


MyDate = Date

'DaysInMonth = EoMonth(Today(), 0)

DaysLeft = WorksheetFunction.EoMonth(Date, 0) - Date

'MsgBox DaysLeft

DaysInMonth = (MonthDays(Month(MyDate)))

'MsgBox DaysInMonth

PercentLeft = DaysLeft / DaysInMonth

'MsgBox PercentLeft

Set rngData = ThisWorkbook.Worksheets("Ingredient_Forecast_Summary").Range("G3:G70")
rngData = Evaluate(rngData.Address & "*PercentLeft.value")


End Sub

1 个答案:

答案 0 :(得分:1)

LPerry。试试这个:

Sub MultiplyDayRatio()

    Dim rngData As Range, C As Range '<-- new variable
    Dim MyDate As Date
    Dim DaysLeft As Integer
    Dim DaysInMonth As Integer
    Dim PercentLeft As Double


    MyDate = Date

    'DaysInMonth = EoMonth(Today(), 0)

    DaysLeft = WorksheetFunction.EoMonth(Date, 0) - Date

    'MsgBox DaysLeft

    DaysInMonth = (MonthDays(Month(MyDate)))

    'MsgBox DaysInMonth

    PercentLeft = DaysLeft / DaysInMonth

    'MsgBox PercentLeft

    Set rngData = ThisWorkbook.Worksheets("Ingredient_Forecast_Summary").Range("G3:G70")
    'rngData = Evaluate(rngData.Address & "*PercentLeft.value") 'instead this

    'Try this
    For Each C In rngData
        C = C * PercentLeft
    Next C

End Sub