使用文本文件为Access窗体中的字段提供默认值

时间:2014-04-14 16:57:56

标签: vba ms-access ms-access-2007 access-vba ms-access-2010

我在Microsoft Access中有一个弹出窗口,其中包含需要由用户填写的文本框字段,例如:

First Name:
Last Name:

现在我尝试创建一个按钮,点击后会查看C:\ mytextfile.txt 并自动填充这些字段。

在文本文件中,它看起来像这样:

##$@#%#$543%#$%#$$#%LAST NAME:BOB#$#@$@#$@#$@#FIRST NAME:DERRICK$#%$#%$#%#$%$#%$#

所以基本上我正在寻找三件事:

  1. 访问文本文件
  2. 解析数据
  3. 将其填充到文本框中。 (在点击" SAVE"按钮")之前,数据不需要进入表格。
  4. 更新: 这是我到目前为止所写的内容,我不确定它为什么不起作用。

    Private Sub LoadText_Click()
    
        Dim myFile As String myFile = "C:\myFile.txt"
        Me.NameofTextbox = Mid(myFile, 7, 3)
    
    End Sub
    

1 个答案:

答案 0 :(得分:1)

此处为您提供的文件示例以及名为txtboxLastNametxtboxFirstName

的表单上的控件
Dim mFields() As String ' array with fields' names in file
Dim mControls() As String ' corresponding controls' names
Dim mStopChars() As String ' Characters that put after values

Dim tmpstr As String
Dim content As String

Dim i As Long
Dim fStart  As Long
Dim valStart As Long
Dim valEnd As Long
Dim FieldValue As String
Dim j As Long
Dim tmp As Long

' prepare maps

' here : included in field name for common case
mFields = Split("LAST NAME:,FIRST NAME:", ",") 
mControls = Split("txtboxLastName,txtboxFirstName", ",")
mStopChars = Split("#,$,@,%", ",")

' read file into string
Open "c:\mytextfile.txt" For Input As #1

Do While Not EOF(1)
    Input #1, tmpstr
    content = content & tmpstr
Loop

Close #1

' cycle through fields and put their values into controls
For i = LBound(mFields) To UBound(mFields)
    fStart = InStr(1, content, mFields(i))
    If fStart > 0 Then
        valStart = fStart + Len(mFields(i))  'value start at this pos
        'cycle through possible stop chars to locate end of current value
        valEnd = Len(content)
        For j = LBound(mStopChars) To UBound(mStopChars)
            tmp = InStr(valStart, content, mStopChars(j))
            If tmp > 0 Then
                If tmp <= valEnd Then
                    valEnd = tmp - 1
                End If
            End If
        Next j
        ' cut value
        FieldValue = Mid(content, valStart, valEnd - valStart + 1)
        ' assign to control
        Me.Controls(mControls(i)).Value = FieldValue
    End If
Next i
相关问题