2012-07-06 100 views
1

我有一些代码填充名为text5 Forms!Form3!text5的文本框。但每次我点击更新这个文本框的按钮刷新它。MS Access文本框更新/追加

我喜欢它,所以文本保持不变,每次单击按钮时添加新数据。我重视的代码,我至今

Option Compare Database 

Private Sub Command0_Click() 

    Set db = CurrentDb 

    Dim I As Integer 
    Dim varNumber As Integer ' this takes the number for how many times to loop 
    Dim strQueryName As String ' this is for the sql to find lowest rack number 
    Dim P As Integer 'this value is the prod number 
    Dim x As Integer 'value from lowestrackSQL 



    varNumber = Me.Quantity 'box from form me means this form 
    prodnumber = Me.ProdNo 'box from form 

    strQueryName = "SQLToFindLowestRackNumber" 'this will be used to execute the query 


    strSQL = CurrentDb.QueryDefs(strQueryName).sql ' this stores the sql but does not run it 

    Forms!form3!txtPrint = strResult 
    'Stop 

    For I = 1 To varNumber ' uses the quntity value to count how many times to loop 

    x = DLookup("locationrack", strQueryName) 'puts value of query into value x 
    prod# = prodnumber 

    'below puts into imediate view box 
    Debug.Print "Line number = " & I; "; Rack Location = " & x; "; Product Number = " & prod#; ";" 
    'below puts it into form3 text box 
    strResult = strResult & " Line Number = " & I & " Rack Location = " & x & " Product Numner = " & prod# & vbCrLf & "" 
    Forms!form3!Text5 = strResult 


    'below executes the SQL 
    DoCmd.SetWarnings False 
    DoCmd.RunSQL "UPDATE [Location] SET [Location].ID = 0 WHERE [Location].RackID =" & x 
    DoCmd.SetWarnings True 

Next I 



End Sub 

做正如你所看到的strResult值传递到文本框,我只是想继续增加值,以我重新启动甚至在文本框中再次循环。

回答

1

尝试宣告strResult的循环之外与其他变量:

Dim I As Integer 
Dim varNumber As Integer ' this takes the number for how many times to loop 
Dim strQueryName As String ' this is for the sql to find lowest rack number 
Dim P As Integer 'this value is the prod number 
Dim x As Integer 'value from lowestrackSQL 
Dim strResult as String 

因为它是我认为每一次清除它,因为它的范围内,仅限于循环

而且,当你说

Forms!form3!txtPrint = strResult 

添加下面

strResult = Forms!form3!text5 
+0

strResult不循环(我猜它在模块/类级别)的内部声明。即使它是vba范围规则是...不同。一旦变量被声明,即使它是一个循环,它也不会被重新初始化。另一个奇怪的事实是,如果它是在循环中声明的,它可以在循环后用于相同的方法。这可能就是为什么vba程序员倾向于在顶部声明一切。 – 2012-07-06 22:00:01

+0

我猜它没有被声明,正如“Option Compare Database”所证明的那样,它通常表示文件的顶部,更重要的是缺少“Option Explicit”和“Dim P As Integer”的声明价值是产品编号 '随着'prodnumber'的后续使用而没有声明。无论如何,我建议的变化应该使其工作,如果不理想 – Ghost 2012-07-06 22:05:48

+0

啊我错过了。 – 2012-07-06 22:25:26

1
Forms!Form3!Text5 = strResult 

... 覆盖文本框与变量的值的内容。

追加的价值,而不是覆盖它,你需要这样做:

Forms!Form3!Text5 = Forms!Form3!Text5 & strResult