You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何精简重复代码?不同窗体下VB代码的简化方法问询

精简重复代码的方案

核心思路

将两个分支里完全重复的逻辑抽离,先根据type获取对应的目标窗体实例,再统一执行赋值操作,彻底消除代码冗余。

精简后的代码

Dim sourceForm As Object
' 根据type匹配对应的源窗体
Select Case type
    Case "Internal"
        Set sourceForm = frm_internal
    Case "External"
        Set sourceForm = frm_ExternalCanvass
End Select

' 统一执行赋值逻辑
If Not sourceForm Is Nothing And sourceForm.editrow Then
    txtProduct.Enabled = False
    txtProduct.Text = sourceForm.pr_code
    txtDesc.Text = sourceForm.description
    txtUnit.Text = sourceForm.UOMstr
    txtQTY.Text = sourceForm.qty
    txtPurpose.Text = sourceForm.remarks
    uom_id = sourceForm.UOM
End If

show_info(txtProduct.Text)
txtQTY.Focus()

进阶优化(可选)

如果这两个窗体基于同一基类或实现了相同的接口,可以把sourceForm的类型从Object改为对应的窗体类,这样能获得编译时类型检查,避免属性名拼写错误。比如假设两个窗体都继承自BaseProductForm:

Dim sourceForm As BaseProductForm
Select Case type
    Case "Internal"
        Set sourceForm = frm_internal
    Case "External"
        Set sourceForm = frm_ExternalCanvass
End Select
' 后续赋值逻辑与上述一致

内容的提问来源于stack exchange,提问作者Raffy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 23:18:12