我正在创建一个具有多个复选框的用户窗体,我要在其中计算/汇总所选复选框,并显示在用户窗体本身中。
估算按钮的代码:
Private Sub preflight_calculate_Click()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Preflight")
With ws
LastRow = .Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
For j = 0 To us_mp0.Selected - 1
lbValue = us_mp0.Selected(j)
If .Cells(i, "A").Value = lbValue Or _
.Cells(i, "A").Value = Val(lbValue) Then
preflight_resource = Val(preflight_resource) + Val(.Cells(i, "G").Value)
preflight_time = Val(preflight_time) + Val(.Cells(i, "I").Value)
End If
Next
Next
End With
End Sub
在用户窗体中,您可以看到P0,P1,P2,因此这些只在excel工作表中具有值,并且从那里我只需要计算所选复选框的总数
有什么想法吗?在此先感谢
答案 0 :(得分:0)
最好的方法是:
重命名所有复选框,以反映任务和移动/桌面值(例如“ US-P0 | Mobile”,““ US-P2 | Mobile”,...“)
遍历所有控件(例如:For Each ctl In Me.Controls
)
选择“ chekbox”类型的(例如If TypeName(ctl) = "CheckBox" Then
)
将其名称拆分为所需的字符串(例如:task = Split(taskString, "|")(0)
,mobileOrDesktopOffset = IIf(Split(taskString, "|")(1) = "Mobile", 0, 1)
)
最终求和
您可以尝试执行此代码,该代码不需要如上所述重命名复选框,(但您确实应该这样做。.):
Private Sub preflight_calculate_Click()
Dim preflight_resource As Double, preflight_time As Double
Dim taskRng As Range
Dim taskString As Variant
Dim task As String, mobileOrDesktopOffset As Long
With ThisWorkbook.Sheets("Preflight")
With .Range("A1", .Cells(.Rows.Count, 1).End(xlUp))
preflight_resource = Val(Me.preflight_resource)
preflight_time = Val(Me.preflight_time)
For Each taskString In GetTasks
task = Split(taskString, "|")(0)
mobileOrDesktopOffset = IIf(Split(taskString, "|")(1) = "Mobile", 0, 1)
Set taskRng = .Find(what:=task, lookat:=xlWhole, LookIn:=xlValues)
preflight_resource = preflight_resource + taskRng.Offset(, 5 + mobileOrDesktopOffset).Value
preflight_time = preflight_time + taskRng.Offset(, 7 + mobileOrDesktopOffset).Value
Next
End With
End With
With Me
.preflight_resource.Text = preflight_resource
.preflight_time.Text = preflight_time
End With
End Sub
Function GetTasks() As Variant
Dim ctl As Control
Dim mobileLeft As Long, desktopLeft As Long
With Me
For Each ctl In .Controls
If TypeName(ctl) = "CheckBox" Then
If ctl.Value Then
GetTasks = GetTasks & " " & ctl.Parent.Caption & "-" & ctl.Caption & "|" & GetMobileOrDesktop(ctl)
End If
End If
Next
End With
GetTasks = Split(Trim(GetTasks))
End Function
Function GetMobileOrDesktop(ctl As Control) As String
Dim ctl1 As Control
For Each ctl1 In ctl.Parent.Controls
If ctl1.Caption = "Mobile" Then
If ctl1.left = ctl.left Then
GetMobileOrDesktop = "Mobile"
Else
GetMobileOrDesktop = "Desktop"
End If
Exit For
End If
Next
End Function
答案 1 :(得分:0)
您可以将类与以下内容一起使用,其余的可以留给您自学:
realm