我有一个VBA代码,可以从MS Access或Excel应用程序运行。
在代码的一部分(如下所示)中,我必须找到默认的应用程序文件目录,以保存CSV文件。
代码在Excel中运行没有任何错误,但在MS Access中,编译器抱怨
代码有什么问题?我有其他的方法来找到文件路径适用于MS Access和Excel??
If CSVpath = vbNullString Then
Select Case Application.Name '' system in which the code is running from
Case Is = "Microsoft Excel" '' it raises an error in MS Access
CSVpath = Application.ThisWorkbook.Path + "DataSet_" + CStr(Format(Now(), "YYYY-MM-DD.HH.MM.SS")) + ".csv"
Case Is = "Microsoft Access"
CSVpath = Application.CurrentProject.Path + "DataSet_" + CStr(Format(Now(), "YYYY-MM-DD.HH.MM.SS")) + ".csv"
Case Else
CSVpath = ""
End Select
End If
我会这样尝试,使用字符串变量转换Application
的主要文档对象。
这样,如果你以后改变了对文件名的想法,你只需要在一个地方修改它。
此外,我还添加了一个检查文件尚未保存的可能性(那时它将没有路径)
Sub Test()
Dim DocObjName As String
Dim DocPath As String
Dim CSVFullFilename As String
Select Case Application.Name
Case "Microsoft Excel"
DocObjName = "ThisWorkbook"
Case "Microsoft Access"
DocObjName = "CurrentProject"
Case "Microsoft Word"
DocObjName = "ActiveDocument"
Case "Microsoft PowerPoint"
DocObjName = "ActivePresentation"
Case Else
' if it stops here, you know you have made a programming error to fix
' add another case based on the application you are using?
' do not just set it to an empty string and let it continue
Stop
Exit Sub
End Select
DocPath = CallByName(Application, DocObjName, VbGet).Path
If Len(DocPath) = 0 Then
MsgBox "Error: File has not yet been saved, so there is no path to use", vbCritical
Exit Sub
Else
CSVFullFilename = DocPath & "DataSet_" & Format(Now(), "YYYY-MM-DD.HH.MM.SS") & ".csv"
End If
Debug.Print CSVFullFilename
End Sub
为了更好的变量命名,我会使用CSVFullFilename
而不是CSVpath
,因为它不仅仅是一个路径-但这只是个人偏好。
对于MS-Access尝试:
Application.StartupPath & "your resource database name"
- 应用程序。StartupPath会给你可执行文件的位置。
- ,你的资源数据库名称"是文件的名称。确保将它与。exe 放在同一个文件夹中