此代码将查看每个工作表名称并在组合框中列出它们。当您选择其中一个工作表时,它将从最后一行中获取值并将它们放在表单上的文本框中。
将这些控件添加到用户窗体:
- 组合框称为
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(转换为美国日期格式)。
使用该代码将在表单上显示日期为01-May-16。
同样应添加货币,否则£15将显示为15。
Me.txtColC = Format(.Cells(rLastCell.Row, 3), "dd-mmm-yy")
Me.txtColB = Format(.Cells(rLastCell.Row, 2), "Currency")
如果您想排除某些工作表,请查看SELECT CASE...END SELECT
代码块(或IF...ELSE...END IF
)
如果您希望在组合框中选择不同的值时更改工作表,只需添加shtSelected.Select
到cmbSheets_Change()
事件的末尾。