【发布时间】:2015-07-24 09:59:19
【问题描述】:
我有这个 VBA 代码可以检查文件夹中的所有文件。如果文件不是 pdf,则它会打开它。然后循环遍历文本中的每个段落,如果该段落包含一些固定符号,它会将段落文本和值导出到 Access DB。
代码在 80% 的情况下都能正常工作,但其他时候,我收到一条错误消息:
对象变量或未设置块变量”错误。
这是我的代码:
Sub retrieve()
Dim wfile, strinsert, fileorigine, parastringa, parastring, myOutput, price, quantity, filename As String
Dim Myrange As Range
Dim objPara
Dim accessdb As Access.Application
Dim para As Paragraph
Dim date_created, date_last_modified As Date
Dim currfile As Document
Application.DisplayAlerts = False
Set accessdb = CreateObject("Access.Application")
With accessdb
.OpenCurrentDatabase ("C:\Users\myuser\Desktop\macro\DataBaseFr.accdb")
.Visible = True
.DoCmd.SetWarnings False
For i = 0 To 100 'This will have to be updated with a counter
If i = 0 Then ' For the first call to dir
wfile = Dir("C:\Users\myuser\Desktop\macro\doc\")
Else
wfile = Dir 'all calls to Dir after the first
End If
'if .pdf then skip
If Right(wfile, Len(wfile) - InStrRev(wfile, ".")) = "pdf" Then
Else
Set currfile = Documents.Open("C:\Users\myuser\Desktop\macro\doc\" & wfile)
'for each paragraph
fileorigine = Replace(Left(currfile.Name, (InStrRev(currfile.Name, ".", -1, vbTextCompare) - 1)), "'", "")
date_last_modified = Format(FileDateTime(currfile.FullName), "d/m/yy h:n ampm")
date_created = currfile.BuiltInDocumentProperties("Creation Date")
For Each para In currfile.Paragraphs
Set objPara = para.Range
objPara.Find.Text = "€"
objPara.Find.Execute
'if the line contains €
If objPara.Find.Found Then
If Left(para.Range.Text, 7) = "Sum" Then
'if the line contains € AND Sum
parastringa = para.Previous.Range.Text
parastring = parastringa
quantity = Trim(Left(para.Range.Text, (InStrRev(para.Range.Text, "€") - 1)))
price = Trim(Right(para.Range.Text, ((Len(para.Range.Text) - InStrRev(para.Range.Text, "€")))))
Else 'if it is not a sum line
parastringa = para.Range.Text
parastring = Trim(Left(parastringa, (InStrRev(parastringa, "€") - 1)))
price = Trim(Right(parastringa, ((Len(parastringa) - InStrRev(parastringa, "€")))))
quantity = ""
End If
strinsert = " INSERT INTO Base " & "([origin], [Description],[date_created],[Datelast],[quantity], [price]) VALUES ('" & fileorigine & "', '" & parastring & "', '" & date_created & "' , '" & date_last_modified & "', '" & quantity & "' , '" & price & "');"
CurrentDb.Execute strinsert, dbFailOnError
Else
End If
Next para
currfile.Close SaveChanges:=False
End If
i = i + 1
Next
CurrentDb.Close
End With
Application.DisplayAlerts = True
End Sub`
可能会发生什么,我该如何解决?
【问题讨论】:
-
从适当调暗变量开始 - 如日期所示。
-
你的意思是把所有的 Dims 放在同一行会导致问题吗?
-
错误发生在哪里?代码在哪一行失败?
-
如果没有如图所示特别变暗,变量将变暗为变体。
-
Dim date1, date2 AS Date为您提供 date1 作为变体和 date2 作为日期。第一个的类型没有说明,所以 VBA 使它成为一个变体。但是Dim date1 AS Date, date2 AS Date为您提供了 2 个日期类型变量。