Excel VBA: 初始化用户窗体时搜索 sheet 特定字符串

Excel VBA: Search sheet for specific string when initializing userform

我正在尝试探索 VBA 中的一些可能性,并想创建一个费用跟踪 sheet。 (我的将专门用于体育博彩,因为在我居住的地方它是合法的,但可以更改为家庭开支、差旅费等)

用户输入赌注(第 1 行)并通过单独的用户表单

将其结果设置为 "Not Decided"

然后当比赛决定时,用户需要通过另一个用户表单更新该投注的结果,这是我目前遇到的问题。我希望我能让表格有两个文本框,其中包含相关信息(下注日期和描述),其中填充了结果设置为 "Not Decided" 的行中的数据。

我尝试 assemble 的代码运行没有错误,但不输出任何内容如下。我试图添加一个带有 "Beskrivelse" 变体的消息框,但它返回的是空的。我不知道它是否运行正确但没有保存单元格的值,或者它是否在正确的位置查找。

Private Sub UserForm_Initialize()

Dim sht As Worksheet
Dim finalrow As Long

Dim Beskrivelse As String 'description of bet'
Dim Dato As Date 'date of bet'

Dim i As Integer 'row counter'

Set sht = ThisWorkbook.Worksheets("FormelIndtastninger") 'needs to look up data from this specific sheet'
finalrow = sht.ListObjects("Data").Range.Rows.Count 'final row in Data table'

For i = 2 To finalrow
    If Cells(i, 9) = "Ikke Afgjort" Then
        Beskrivelse = Cells(i, 6)
        Dato = Cells(i, 1)
        End If
Next

OpdaterIndtastning.DatoTekstboks.Text = Dato
OpdaterIndtastning.SpilTekstboks.Text = Beskrivelse

End Sub

除了 Mathieu Guindon 建议使用 UserForm_Activated 事件而不是 UserForm_Initialize 事件。使用 Cell(row,column) 在当前上下文中不起作用。我想如果您尝试下面的代码,您会发现问题已解决。

'Change finalrow from long to range
'Old Code Dim finalrow as Long
Dim finalrow as Range
Set finalrow = sht.ListObjects("Data").Range.Rows  'Sets finalrow = to entire data table range

'The range below as the index of your for loop
Dim aRow as Range
For Each aRow In finalrow 
    If aRow.Value2(1, 9) = "A" Then
        Beskrivelse = aRow.Value2(1, 6)
        Dato = aRow.Value2(1, 1)
    End If
Next