How to Split a String and Store in MS Access table

雨燕双飞 提交于 2021-01-28 12:10:55

问题


I would like to be able to split a string of text that has been entered into a textbox on a MS Access form and store the split strings as separate records under the same field. This is the code I have so far, but I keep running into problems at every corner. I'm fairly new to this, but have been learning quickly. Any help is appreciated.

Here is what I'd like to accomplish: If I enter the following text into a text box ("this is a sentence") and click submit. I would like each other the words to be stored as individual records under a common field. Seems simple, but it's causing quite a few headaches.

Private Sub Submit_Click()

    Dim SetDBConnection As ADODB.Connection
    Set SetDBConnection = CurrentProject.Connection

    Dim strInsertRecord As String

    Dim strNewPhrase As String
    Dim strStorePhrase As String

    strNewPhrase = textPhrase
    strStorePhrase = Split(NewPhrase)

    strInsertRecord = "INSERT INTO [FieldSplice] (words) VALUES (" & strStorePhrase & ")"
    SetDBConnection.Execute strInsertRecord

    textPhrase.Value = Null
End Sub

回答1:


I'm a little unclear on why you have the ADODB connection... is this connecting to an external database? If so, that makes sense, but then you are missing some code to get the insert to work properly.

If this is just an internal (native) Access table, then I don't think you need any of that. Here is a simple example of how you would take a string, split it into words (based on a space) and then insert those into your table:

Dim textPhrase As String
Dim words() As String
Dim i As Integer

textPhrase = "This is a test"
words = Split(textPhrase, " ")

sql = "parameters P1 text; INSERT INTO [FieldSplice] (words) VALUES ([P1])"

Set query = CurrentDb.CreateQueryDef("FsInsert", sql)

For i = LBound(words) To UBound(words)
  query.Parameters("P1").Value = words(i)
  query.Execute
Next i

CurrentDb.QueryDefs.Delete ("FsInsert")

One other note of interest -- you don't need to declare the insert each time. You can set a parameter, assign values to the parameter and execute the insert command multiple times. This is included in my example above.

Your code was trying to say:

insert into [table] (field) values ("value1", "value2", "value3")

Which you can't do. That has to be done as three inserts, unless your database supports array inserts (Oracle, for example).

The multiple fields only works like this:

insert into [table] (field1, field2) values ("value1", "value2")

Where each value corresponds to a column in the table.



来源:https://stackoverflow.com/questions/34443316/how-to-split-a-string-and-store-in-ms-access-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!