我有一个很长的文本字段(称为“reporttext”),有人正在导入一堆需要分离并附加到另一个表中的文本。对于每种情况,都有一个“[]”字符,用于分隔每个案例。我希望我的代码查找第一个[]和第二个[],将文本追加到另一个表然后循环。所以下一个案例是第二个[]和第三个[]之间的文本。
这是我的字符串
报告文字:[] ksfj jls [] 42244 [] @@@@
我希望这可以附加到一个名为“notes”的新表中,它将是这样的:
报告文字 ksfj jls 42244 @@@@
我使用宏来计算文本文件中[]的数量,以了解运行循环的次数,但是这和我的其余代码一起发生的情况并没有发生。我知道我的代码是错误的,但我知道通过一些调整它会到达那里。任何帮助表示赞赏。
lengthofnote = Len([reporttext])
start = InStr([reporttext], "[]")
startplus3 = [start] + 3
'find number of cases
firstcase = 1
numcases = StringCountOccurrences([reporttext], "[]")
Dim LCounter As Integer
For LCounter = [firstcase] To [numcases]
revisedreporttext = Mid([reporttext], [startplus3], [lengthofnote])
secondposition = InStr([revisedreporttext], "[]")
nextreporttext = Mid([reporttext], [startplus3], [secondposition])
Add_reporttext = "INSERT INTO notes(reporttext) values ('" & nextreporttext & "');"
DoCmd.RunSQL Add_reporttext
firstcase = firstcase + 1
startplus3 = secondposition
secondposition = secondposition + 4
Next LCounter
@Zev Spitz是正确的,你可以使用Split()
来实现这一目标。你可以使用这样的东西
Option Compare Database
Option Explicit
Sub SplitLongTextField()
Dim rs As Recordset
Dim reportTextArr
Dim qString As String
Dim i As Long
qString = "SELECT [reporttext] FROM [Table1]" '<- replace [Table1] with the name of your table with the Long Text field
Set rs = CurrentDb.OpenRecordset(qString)
If Not rs.EOF Then
reportTextArr = Split(rs.Fields("reporttext"), "[]")
End If
For i = LBound(reportTextArr) To UBound(reportTextArr)
If Not reportTextArr(i) = "" Then
DoCmd.RunSQL "INSERT INTO notes(reporttext) VALUES('" & reportTextArr(i) & "');"
End If
Next i
rs.Close
End Sub
如果您需要从初始表中为多个记录执行此操作,那么您可以循环遍历整个表并循环操作
Option Compare Database
Option Explicit
Sub SplitLongTextField()
Dim rs As Recordset
Dim reportTextArr
Dim qString As String
Dim i As Long
qString = "SELECT [reporttext] FROM [Table1]" '<- replace [Table1] with the name of your table with the Long Text field
Set rs = CurrentDb.OpenRecordset(qString)
Do Until rs.EOF
reportTextArr = Split(rs.Fields("reporttext"), "[]")
For i = LBound(reportTextArr) To UBound(reportTextArr)
If Not reportTextArr(i) = "" Then
DoCmd.RunSQL "INSERT INTO notes(reporttext) VALUES('" & reportTextArr(i) & "');"
End If
Next i
rs.MoveNext
Loop
rs.Close
End Sub
假设字符串始终以[]
开头,而preference是返回单个字符串,请考虑:
Replace(Mid(reporttext, 4), "[] ", vbCrLf)