有没有一种方法可以根据用户表单输入选择表?

时间:2019-10-22 22:16:14

标签: excel vba

我创建了一个通用用户窗体,用户可以在该窗体上从组合框中选择建筑物位置。这被绑定到与该位置同名的图纸上。我希望拥有它,以便当他们按下Enter键时,表单上的数据将输入到相应页面的表格中。由于表格必须具有一个唯一的名称,该名称在所有工作表中都不能重复,因此我在如何使用字符串设置表格范围方面感到困惑。我使用以下格式命名所有表:TableSheetname。有没有办法设置等于“ Table”和Sheetname的字符串?

Dim oNewRow As ListRow, rng As Range, tbl As String

Set tbl = "Table" & sht

Set rng = Worksheets(sht).Range(tbl)
rng.Select
Set oNewRow = Selection.ListObject.ListRows.Add(AlwaysInsert:=True)
With ws
        oNewRow.Range.Cells(1, 1).Value = Me.box1.Value
        oNewRow.Range.Cells(1, 2).Value = Me.box2.Value
        oNewRow.Range.Cells(1, 3).Value = Me.box3.Value
        oNewRow.Range.Cells(1, 4).Value = Me.box4.Value
        oNewRow.Range.Cells(1, 5).Value = Me.box5.Value
        oNewRow.Range.Cells(1, 6).Value = Me.box6.Value
End With

2 个答案:

答案 0 :(得分:0)

这将选择2个表-table1table2,一个接一个:

Sub TableSelector()

    Dim tableName As String
    Dim i As Long

    For i = 1 To 2
        Worksheets(1).Range("table" & i).Select
        Stop
    Next i        

End Sub

只需确保从用户窗体传递i

enter image description here

答案 1 :(得分:0)

也许我读错了它,但听起来您想从组合框中获取工作表名称以选择正确的表。

'updated as it looks like your logic is in the actual form

'Lets say your combobox name is ComboBox1 (since oyu did not supply that)

Dim oNewRow As ListRow, rng As Range, tbl As String
Dim sht As String
sht = Me.ComboBox1.Text
tbl = "Table" & sht

Set rng = Worksheets(sht).Range(tbl)
rng.Select
Set oNewRow = Selection.ListObject.ListRows.Add(AlwaysInsert:=True)
With ws
    oNewRow.Range.Cells(1, 1).Value = Me.box1.Value
    oNewRow.Range.Cells(1, 2).Value = Me.box2.Value
    oNewRow.Range.Cells(1, 3).Value = Me.box3.Value
    oNewRow.Range.Cells(1, 4).Value = Me.box4.Value
    oNewRow.Range.Cells(1, 5).Value = Me.box5.Value
    oNewRow.Range.Cells(1, 6).Value = Me.box6.Value

End With