Excel VBA:初始化用户表单时在工作表中查找特定的字符串

时间:2018-09-20 17:04:39

标签: excel vba excel-2016

我正在尝试探索VBA中的一些可能性,并希望创建一个费用跟踪表。 (由于我的住所合法,我的地点将专门用于体育赌博,但可能会更改为家庭支出,旅行支出等。)

用户输入赌注(1排),并通过单独的用户表格将其结果设置为“未决定”

然后,在决定游戏后,用户需要通过另一种用户表格(该卡目前是我当前停留的位置)来更新该下注的结果。我希望我可以使表单具有两个带有相关信息(下注日期和描述的信息)的文本框,这些文本框填充行中的数据并将结果设置为“未决定”。

我尝试汇编的代码在没有错误的情况下运行,但是下面没有任何输出。我尝试添加带有“ 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

1 个答案:

答案 0 :(得分:0)

除了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