我有一个包含客户信息的工作簿。每个客户都有一张表,每张表都标有客户的唯一ID。我想要启动一个UserForm,用户将从一个cobo框中选择一个客户端。然后,来自相应工作表的最后一行的数据填充UserForm。
在同一工作簿中的其他代码中,我使用的是脚本字典,但这些字典都与特定工作表中的特定范围相关联。我不知道如何编写UserForm代码来搜索所有工作表以找到与cobo_ClientID字段中的值具有相同名称的工作表,然后从具有MAX更新日期的行中引入正确的数据元素。
这是我在其他领域使用的脚本字典的示例:
Set coboDict = CreateObject("Scripting.Dictionary")
With coboDict
For Each cStatsClientID In ws1.Range("StatsClientID")
If Not .exists(cStatsClientID.Value) Then
.Add cStatsClientID.Value, cStatsClientID.Row
Else
If CLng(cStatsClientID.Offset(, -2).Value) > CLng(ws1.Range("B" & .Item(cStatsClientID.Value))) Then
.Item(cStatsClientID.Value) = cStatsClientID.Row
End If
End If
Next cStatsClientID
Me.cobo_ClientID.List = Application.Transpose(.keys)
End With
在提供的LastRow链接和另一个论坛的一些建议之间,我认为我有解决方案。问题似乎与我如何设置LastRow以及找到正确的表格有关。
Private Sub cobo_ClientID_Change()
Dim Sht As String
Dim LastRow As Long
Sht = Me.cobo_ClientID
With ActiveSheet
LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row
End With
txt_Name = Sheets(Sht).Range("E" & LastRow).Value
txt_DPPymtAmt = Sheets(Sht).Range("H" & LastRow).Value
End Sub
此代码将查看每个工作表名称并在组合框中列出它们。当您选择其中一个工作表时,它将获取最后一行中的值并将它们放在表单上的文本框中。
将这些控件添加到用户窗体:
cmbSheets
txtColA
,txtColB
和txtColC
。-
Private Sub UserForm_Initialize()
Dim wrkSht As Worksheet
'Populate the combo-box with sheet names.
For Each wrkSht In ThisWorkbook.Worksheets
With Me.cmbSheets
.AddItem wrkSht.Name
End With
Next wrkSht
End Sub
'Will place the values from the last row columns A:C in textboxes on the form.
Private Sub cmbSheets_Change()
Dim rLastCell As Range
Dim shtSelected As Worksheet
'Set a reference to the sheet selected by the combo box.
Set shtSelected = ThisWorkbook.Worksheets(cmbSheets.Value)
Set rLastCell = LastCell(shtSelected)
With shtSelected
Me.txtColA = .Cells(rLastCell.Row, 1)
Me.txtColB = .Cells(rLastCell.Row, 2)
Me.txtColC = .Cells(rLastCell.Row, 3)
End With
End Sub
'This function can be placed in a normal module.
'Finds the last cell given a worksheet reference.
Public Function LastCell(wrkSht As Worksheet) As Range
Dim lLastCol As Long, lLastRow As Long
On Error Resume Next
With wrkSht
lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
lLastRow = .Cells.Find("*", , , , xlByRows, xlPrevious).Row
If lLastCol = 0 Then lLastCol = 1
If lLastRow = 0 Then lLastRow = 1
Set LastCell = wrkSht.Cells(lLastRow, lLastCol)
End With
On Error GoTo 0
End Function
注意 - 如果任何值需要某些格式,则应在复制时使用FORMAT
命令添加。
例如。如果单元格的2016年5月1日日期为01/05/2016,则它将在文本框中显示为5/1/2016(转换为美国日期格式)。
使用代码Me.txtColC = Format(.Cells(rLastCell.Row, 3), "dd-mmm-yy")
将在表单上显示日期为01-May-16。
同样,货币应该添加为Me.txtColB = Format(.Cells(rLastCell.Row, 2), "Currency")
,否则15英镑将显示为15。
如果你想排除某些表,看看SELECT CASE...END SELECT
代码块(或IF...ELSE...END IF
)
如果您希望在组合框中选择不同的值时更改工作表,只需将shtSelected.Select
添加到cmbSheets_Change()
事件的末尾即可。