Access交流中心

北京 | 上海 | 天津 | 重庆 | 广州 | 深圳 | 珠海 | 汕头 | 佛山 | 中山 | 东莞 | 南京 | 苏州 | 无锡 | 常州 | 南通 | 扬州 | 徐州 | 杭州 | 温州 | 宁波 | 台州 | 福州 | 厦门 | 泉州 | 龙岩 | 合肥 | 芜湖 | 成都 | 遂宁 | 长沙 | 株洲 | 湘潭 | 武汉 | 南昌 | 济南 | 青岛 | 烟台 | 潍坊 | 淄博 | 济宁 | 太原 | 郑州 | 石家庄 | 保定 | 唐山 | 西安 | 大连 | 沈阳 | 长春 | 昆明 | 兰州 | 哈尔滨 | 佳木斯 | 南宁 | 桂林 | 海口 | 贵阳 | 西宁 | 乌鲁木齐 | 包头 |

能简化这个条件吗

半夜罗  发表于:2019-01-25 15:14:02  
复制

请教各位老师,下面代码中的红色部分是一个比较有规律的数字,能将其简化成类似Excel中的(6:8;16:20)吗?能简化的话请写一下, 谢谢!

Public Function 计算单位成本()

    Dim rst As DAO.Recordset       
    Dim rs累计数量 As Currency   
    Dim b As Currency   
    If (Not IsNull(DLookup("累计数量", "损益表", "id=1"))) Then
        Set rst = CurrentDb.OpenRecordset("SELECT * FROM 损益表 ORDER BY id", dbOpenDynaset)
        rst.MoveFirst    
        rs累计数量 = DLookup("累计数量", "损益表", "id=1")
        Do While Not rst.EOF   
            rst.Edit
            If rst!id = 6 Or rst!id = 7 Or rst!id = 8 Or rst!id = 16 Or rst!id = 17 Or rst!id = 18 Or rst!id = 19 Or rst!id = 20 Then
                b = (rst!累计金额 / rs累计数量) * 1000
                rst!单位成本1 = b
            End If
            rst.Update
            rst.MoveNext
        Loop
        rst.Close   
        Set rst = Nothing    
    End If
End Function

 

Top
西出阳关无故人 发表于:2019-01-25 16:32:45

首先自定义一个函数(基于给定的固定数据):

Public Function inArray(ByVal inid As Long) As Boolean
    Dim ary As Variant
    ary = Array(6, 7, 8, 16, 17, 18, 19, 20)'这里你可以添加更多的条件
    inArray = False
    For i = 0 To UBound(ary)
        If inid = ary(i) Then
            inArray = True
            Exit For
        End If
    Next
End Function
然后把你的if...改为:

if inArray(rst!id)=true then

               b = (rst!累计金额 / rs累计数量) * 1000
                rst!单位成本1 = b

end if

另外,你也可以把条件放在表中,然后用dlookup函数来判定是够符合条件,这种方式更灵活

条件表的字段

id  自动编号

条件  长整型

然后自定义函数:

Public Function InList(ByVal inLong As Long) As Boolean
    Dim rst As Recordset
    If Nz(DLookup("id", "条件表", "条件=" & inLong), 0) = 0 Then'这里获取id,是因为id为自动编号,且永远大于零的特征。
        InList = False
    Else
        InList = True
    End If
End Function

然后把你的if...改为:

if InList(rst!id)=true then

               b = (rst!累计金额 / rs累计数量) * 1000
                rst!单位成本1 = b

end if





半夜罗 发表于:2019-01-25 20:00:55
谢谢老师!

总记录:2篇  页次:1/1 9 1 :