Ms access 如何在Access VBA中自动设置文件夹位置和文件名?

Ms access 如何在Access VBA中自动设置文件夹位置和文件名?,ms-access,vba,Ms Access,Vba,我想替换VB中2个带下划线区域之间的硬代码,如图所示,这样它就可以用代码自动获取excel文件,并将电子表格传输到具有相同字段的Ms Access表中。它应该能够在MS Access中使用vb代码自动执行此功能 Dim fso As Object 'FileSystemObject Dim f As Object 'File Dim strTempPath As String Dim objExcel As Object 'Excel.Application Dim objWorkbook

我想替换VB中2个带下划线区域之间的硬代码,如图所示,这样它就可以用代码自动获取excel文件,并将电子表格传输到具有相同字段的Ms Access表中。它应该能够在MS Access中使用vb代码自动执行此功能

Dim fso As Object  'FileSystemObject
Dim f As Object  'File
Dim strTempPath As String
Dim objExcel As Object  'Excel.Application
Dim objWorkbook As Object  'Excel.Workbook
Const TemporaryFolder = 2

On Error Resume Next
StrSQL = "DELETE * FROM bed_code_tbl"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL

Set fso = CreateObject("Scripting.FileSystemObject")  'New FileSystemObject
strTempPath = fso.GetSpecialFolder(TemporaryFolder) & "\" & fso.GetTempName & "\"
fso.CreateFolder strTempPath
'------------------------------------------------------

Set f = fso.GetFile("C:\Users\johnpfe\Documents\Bed_code_tbl.xlsx")
fso.CopyFile f.Path, strTempPath & f.Name
'--------------------------------------------------------

Set objExcel = CreateObject("Excel.Application")  ' New Excel.Application
Set objWorkbook = objExcel.Workbooks.Open(strTempPath & f.Name)
objWorkbook.ActiveSheet.Range("A1:C100").Select
objWorkbook.Save
Set objWorkbook = Nothing
objExcel.Quit
Set objExcel = Nothing

DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, "bed_code_tbl", 
strTempPath & f.Name, True

fso.DeleteFile strTempPath & f.Name
fso.DeleteFolder Left(strTempPath, Len(strTempPath) - 1)

Set f = Nothing
Set fso = Nothing
端接头
“-------------------------------------------------------------

您可以获取access文件的文件夹位置。并相对于该位置放置创建的文件


或者向用户询问位置。

我假设您正在尝试查找当前用户的文档文件夹。 您可以使用eviron()函数。如果您遵循这些链接,将了解更多信息


用什么代替?简单的答案是初始化一个字符串变量(可能在循环中),然后将该字符串变量设置为所需的文件路径。是否希望通过
CreateObject(“Wscript.Shell”).SpecialFolders(“Mydocuments”)
返回文件夹位置?
Dim fso As Object  'FileSystemObject
Dim f As Object  'File
Dim strTempPath As String
Dim objExcel As Object  'Excel.Application
Dim objWorkbook As Object  'Excel.Workbook
Const TemporaryFolder = 2

On Error Resume Next
strSQL = "DELETE * FROM bed_code_tbl"
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL

Set fso = CreateObject("Scripting.FileSystemObject")  'New FileSystemObject
strTempPath = fso.GetSpecialFolder(TemporaryFolder) & "\" & fso.GetTempName & "\"
fso.CreateFolder strTempPath
'------------------------------------------------------

Set f = fso.GetFile(Environ("UserProfile") & "\Documents\Bed_code_tbl.xlsx")
fso.CopyFile f.Path, strTempPath & f.NAME
'----------------------------------------------------------------------