【发布时间】:2019-09-27 20:44:07
【问题描述】:
我有一个 -userform- 有 100 个不同的控件(文本框和组合框),我正在尝试将一大块代码合并到更小和更通用的东西...通过基于活动控件并将其用作我调用另一个 sub 的参考点,其中声明的变量将变为即插即用。
所以这是有效的基本代码......但我需要复制 25 次,我觉得有更好的方法,但我似乎无法弄清楚......
Option Explicit
Public Gal, Kg, L, Qt, Pt, Lbs, C, FlOz, Ea, Prts, Oz, Tbs, Tsp, Dl, G, Ml As Integer
Private Sub M1_AfterUpdate() 'this is where the math happens
'I have 25 variables, M1:M25 - by 16 variables, Gal:Ml for each
Gal = 128: Kg = 35.274: L = 33.814: Qt = 32: Pt = 16: Lbs = 16: C = 8 'multiply
FlOz = 1: Ea = 1: Prts = 1: Oz = 1 'stay
Tbs = 2: Tsp = 6: Dl = 3.381: G = 28.353: Ml = 29.574 'divide
'this is the base code that does ecactly what I need... But i would have to replicate this whole thing 25 times...
If ActiveControl.Text = "Gal" Then C1.Value = Round(((Q1 * Gal) * (Application.WorksheetFunction.Index(Sheets("Inventory").Range("C6:L1006"), _
Application.WorksheetFunction.Match(I1, Sheets("Inventory").Range("C6:C1006"), 0), 10))), 2)
If ActiveControl.Text = "Kg" Then C1.Value = Round(((Q1 * Kg) * (Application.WorksheetFunction.Index(Sheets("Inventory").Range("C6:L1006"), _
Application.WorksheetFunction.Match(I1, Sheets("Inventory").Range("C6:C1006"), 0), 10))), 2)
If ActiveControl.Text = "L" Then C1.Value = Round(((Q1 * L) * (Application.WorksheetFunction.Index(Sheets("Inventory").Range("C6:L1006"), _
Application.WorksheetFunction.Match(I1, Sheets("Inventory").Range("C6:C1006"), 0), 10))), 2)
' it goes on through each of the variables but i post it all, you get the idea ; )
End Sub
我已经尝试过这条路......这是失败的!!!我不知道如何将其读取为控件名称,它读取为字符串。
我尝试将控制/控件放在前面,但没有用...
Option Explicit
Public Gal, Kg, L, Qt, Pt, Lbs, C, FlOz, Ea, Prts, Oz, Tbs, Tsp, Dl, G, Ml As Integer
Private Sub M1_AfterUpdate() 'this is where the math happens
Dim ActCtrl As Control: Set ActCtrl = ActiveControl.Name
Dim VarA As Integer
Dim x, y, z As String
If ActCtrl = M1 Then VarA = 1 ' 25 if lines written to represent 25 rows of form controls
'M2 is VarA=2 and so on till 25
'this puts them together, but it returns string.
x = "I" & VarA
y = "Q" & VarA
z = "C" & VarA
'this is where it would end
z.Value = Round(((y * Ml) * (Application.WorksheetFunction.Index(Sheets("Inventory").Range("C6:L1006"), _
Application.WorksheetFunction.Match(x, Sheets("Inventory").Range("C6:C1006"), 0), 10))), 2)
我希望能够改变这个...
If ActiveControl.Text = "Gal" Then C1.Value = Round(((Q1 * Gal) * (Application.WorksheetFunction.Index(Sheets("Inventory").Range("C6:L1006"), _
Application.WorksheetFunction.Match(I1, Sheets("Inventory").Range("C6:C1006"), 0), 10))), 2)
使用变量变成即插即用...如果可能的话...
【问题讨论】:
-
在工作表上创建一个两列的查找表,带有Unit & Conversion Factor,并使用vlookup直接将单位转换为缩放值。不过,这只是一个起点,因为它似乎只会处理您拥有的部分重复内容。
标签: excel vba variables controls userform