获取行n和列的单元格(按名称)

时间:2017-11-01 15:17:00

标签: excel-vba userform vba excel

系统说明:我在电子表格(Sheet2,租用日志)中有一个名为 RentLogs 的表格的电子表格。单击按钮时,将显示用户窗体,用户选择返回项目的日期,然后单击“确定”。然后,表单在表格中搜索项目的ID,并在签入日期列中记录签入日期。

enter image description here

问题:

1)我的VBA代码(下面)只能在整个工作表上找到项目ID,如何在表格中找到它的位置,以便移动表格而不必担心静态列值?
2)如何让VBA将其放入(项目ID的行,签入日期列)?

Private Sub checkout_cmdbutton_Click()
    Dim ws As Worksheet
    Set ws = Worksheets("Renting Logs")

    Const WHAT_TO_FIND As Integer = 200

    Set FoundCell = ws.Range("RentLog").Find(What:=WHAT_TO_FIND, SearchOrder:=xlRows, SearchDirection:=xlNext, LookIn:=xlValues)
    If Not FoundCell Is Nothing Then
        MsgBox (WHAT_TO_FIND & " found in (" & FoundCell.Row & "," & FoundCell.Column & ")")
    Else
        MsgBox (WHAT_TO_FIND & " not found in RentLog")
        Exit Sub
    End If

'copy the check in date to the table
    ws.Cells(FoundCell.Row, ws.Range("RentLog").Column).Value = Me.checkin_datepicker.Value

'clear userform
    Me.checkin_datepicker.Value = Date

'close userform
Unload Me End Sub 

我的尝试:我知道问题在于我的搜索算法,但我不熟悉VBA并且不知道对象的所有属性。用户形式完美无缺,所以没问题。

2 个答案:

答案 0 :(得分:0)

要直接回答您的问题,要使用VBA引用表格中的特定列,您可以使用Range("TableName[Column Name]")(实际上,这也是您在Excel公式中引用它的方式:{{1} })。

至于实施,我个人总是去索引匹配。

TableName[Column Name]

前往Private Sub checkout_cmdbutton_Click() Dim ws As Worksheet Set ws = Worksheets("Renting Logs") Const WHAT_TO_FIND As Integer = 200 Dim FoundRow As Variant Dim FoundCell As Range, TargetCell As Range FoundRow = Application.Match(WHAT_TO_FIND, ws.Range("RentLogs[Item ID]"), 0) ' if there is a match of WHAT_TO_FIND in the "Item ID" column of "RentLogs" table, returns a number corresponding to the row, otherwise returns an error If Not IsError(FoundRow) Then ' if there is a match Set FoundCell = Application.WorksheetFunction.Index(ws.Range("RentLogs[Item ID]"), FoundRow) ' get the corresponding cell in the "Item ID" column of "RentLogs" table at the same row as the match, MsgBox (WHAT_TO_FIND & " found in (" & FoundCell.Row & "," & FoundCell.Column & ")") ' you may wish to look at FoundCell.Row and FoundCell.Column, as this is currently relative to the worksheet, not the table Else ' if there is no match MsgBox (WHAT_TO_FIND & " not found in RentLog") Exit Sub End If 'copy the check in date to the table Set TargetCell = Application.WorksheetFunction.Index(ws.Range("RentLogs[Check In Date]"), FoundRow) ' get the corresponding cell in the "Check In Date" column of "RentLogs" table at the same row as the match TargetCell.Value = Me.checkin_datepicker.Value 'clear userform Me.checkin_datepicker.Value = Date 'close userform Unload Me End Sub ,上述内容相当于有一个excel公式,如:

TargetCell

答案 1 :(得分:0)

如果你真的问如何引用表格中的单元格,你可以使用这样的东西。这里有一个有用的语法指南https://www.thespreadsheetguru.com/blog/2014/6/20/the-vba-guide-to-listobject-excel-tables

Dictionaries