【问题标题】:How to specify a different file path for a saved Excel import如何为保存的 Excel 导入指定不同的文件路径
【发布时间】:2014-06-14 13:31:12
【问题描述】:

所以我已经多次使用doCmd.TransferText 来使用保存的文本导入规范,因为您可以轻松地保存从Application.FileDialog(msoFileDialogFilePicker) 返回的文件路径,以使用保存的规范找到您希望导入的文件。

但是我无法找到对 excel 文件执行相同操作的方法,保存 excel 导入规范很简单,但使用 DoCmd.TransferSpreadSheet 方法无法使用保存的导入,也无法使用doCmd.RunSavedImportExport 没有指定文件路径的选项。

除了使用不同的文件类型(例如 .csv)之外,还有什么解决方法

【问题讨论】:

    标签: ms-access vba


    【解决方案1】:

    要添加到@Alberts 答案,如果我们将当前文件路径作为常量,那么,当我们下次运行代码时(例如,用户决定在某个时间后将 excel 文件存储在不同的文件夹中) , 'Replace' 功能将找不到搜索文本,因为在第一次运行时更改了路径。因此,要使其动态化,我们只需要在将当前文件路径替换为新路径时将其写入表即可。在“替换”函数中,我们只引用这个值。文件路径没有硬编码。

    Let Current File Path = DLookup("[Current file path]", "File Path Table")
    Let New File Path  = DLookup("[New file path]", "File Path Table")
    With CurrentProject.ImportExportSpecifications("Saved-Export")
       .XML = Replace(.XML, Current File Path, New File Path)
    End With
    DoCmd.RunSavedImportExport Saved-Export
    
    'Now you write the 'new file path' to the 'current file path' field in the table
    
     Set mydb = DBEngine.Workspaces(0).Databases(0)
     Set myset = mydb.OpenRecordset("File Path Table")
     myset.Edit
         Let myset![Current file path] = New File Path
     myset.Update
     myset.Close
     Set myset = Nothing
     Set mydb = Nothing
    

    所以下次运行时,它会选择正确的当前文件来替换。

    【讨论】:

      【解决方案2】:

      看到这个,我想我会分享一些我为解决问题而努力的东西。更好地控制您可以在规范中更改的内容:

      ' MSXML2 requires reference to "Microsoft XML, v6.0"
      ' earlier versions are probably compatible, remember to use the appropriate DOMDocument object version.
      Sub importExcelFile(ImportSpecName As String, Filename As String, SheetName As String, OutputTableName As String)
          Dim XMLData As MSXML2.DOMDocument60
          Dim ImportSpec As ImportExportSpecification
          Dim XMLNode As IXMLDOMNode
      
          ' Get XML object to manage the spec data
          Set XMLData = New MSXML2.DOMDocument60
      
          XMLData.async = False
          XMLData.SetProperty "SelectionLanguage", "XPath"
          XMLData.SetProperty "SelectionNamespaces", "xmlns:imex='urn:www.microsoft.com/office/access/imexspec'"
              ' need to rename the default namespace, so that we can XPath to it. New name = 'imex'
      
          ' existing Import Specification (should be set up manually with relevant name)
          Set ImportSpec = CurrentProject.ImportExportSpecifications(ImportSpecName)
          XMLData.LoadXML ImportSpec.XML
      
          ' change it's path to the one specified
          With XMLData.DocumentElement
              .setAttribute "Path", Filename
              ' Destination attribute of the ImportExcel node
              Set XMLNode = .SelectSingleNode("//imex:ImportExcel/@Destination")    ' XPath to the Destination attribute
              XMLNode.Text = OutputTableName
              ' Range attribute of the ImportExcel node
              Set XMLNode = .SelectSingleNode("//imex:ImportExcel/@Range")    ' XPath to the range attribute
              XMLNode.Text = SheetName & "$"
          End With
      
          ImportSpec.XML = XMLData.XML
      
          ' run the updated import
          ImportSpec.Execute
      
      End Sub
      

      【讨论】:

      • 我更喜欢这种方法,因为它更健壮;要添加的另一件事是您需要将“Microsoft XML,vX.Y”添加到“添加引用”
      【解决方案3】:

      我研究了同样的问题。 Gord 发布的解决方案给了我一个 XML 解释错误。 Cosmichighway 发布了这个解决方案:http://www.utteraccess.com/forum/index.php?showtopic=1981212

      此解决方案适用于 Access 2010 和 Access 2013,也应该适用于 Access 2007。

      With CurrentProject.ImportExportSpecifications("nameOfSpecification")
          debug.print .XML
          .XML = Replace(.XML, varSavedPathName, varNewPathName)
          debug.print .XML
      End With
      

      我为每次导出生成了一个唯一的文件名,因此在该过程完成后我恢复到原始文件名路径。 WorkHoursTransactions 是一个常量。示例:

      CONST ConstExportSavedPathName="c:\temp\Name Of File To Use.xls"
      
      tmpFileName = WorkHoursTransactions & ";" & Format(Now(), "YYYYMMDD-HHMMSS") & ".xls"
      With CurrentProject.ImportExportSpecifications(WorkHoursTransactions)
          .XML = Replace(.XML, ConstExportSavedPathName, tmpFileName)
          'Debug.Print .XML
      End With
      
      DoCmd.OpenReport WorkHoursTransactions, acViewReport, , , acWindowNormal
      DoCmd.RunSavedImportExport WorkHoursTransactions
      
      ' return to original filename
      With CurrentProject.ImportExportSpecifications(WorkHoursTransactions)
          .XML = Replace(.XML, tmpFileName, ConstExportSavedPathName)
          'Debug.Print .XML
      End With
      

      我还发现了一个使用即时窗口显示 XML 的好技巧。如果您有一个名为“Export-Table1”的导出规范,则可以将其粘贴到即时窗口中以查看 XML:

      ? CurrentProject.ImportExportSpecifications.Item("Export-Table1").XML
      

      【讨论】:

        【解决方案4】:

        就我而言

        vbCrLf 无效 - 但 vbLF 有效!

        我使用的是 Access 2010(32 位)。

        斯特凡的问候

        【讨论】:

          【解决方案5】:

          Access 中的“保存的导入”和“保存的导出”存储在构成CurrentProject.ImportExportSpecifications 集合的ImportExportSpecification 对象中。保存的 Excel 导入的详细信息类似于以下 XML,我通过手动导入 Excel 电子表格并勾选导入向导最后一页上的“保存导入步骤”复选框来创建它。

          <?xml version="1.0" encoding="utf-8" ?>
          <ImportExportSpecification Path = "C:\Users\Gord\Desktop\xlsxTest.xlsx" xmlns="urn:www.microsoft.com/office/access/imexspec">
               <ImportExcel FirstRowHasNames="true" Destination="xlsxTest" Range="Sheet1$" >
                      <Columns PrimaryKey="ID">
                            <Column Name="Col1" FieldName="ID" Indexed="YESNODUPLICATES" SkipColumn="false" DataType="Long" />
                            <Column Name="Col2" FieldName="TextField" Indexed="NO" SkipColumn="false" DataType="Text" />
                            <Column Name="Col3" FieldName="DateField" Indexed="NO" SkipColumn="false" DataType="DateTime" />
                       </Columns>
                  </ImportExcel>
          </ImportExportSpecification>
          

          ImportExportSpecification 以名称Import-xlsxTest 保存。现在,如果我将 Excel 文件从“xlsxTest.xlsx”重命名为“anotherTest.xlsx”,我可以使用以下 VBA 代码更改 ImportExportSpecification 的 XML 中的文件名,然后执行导入:

          Option Compare Database
          Option Explicit
          
          Sub DoExcelImport()
              Dim ies As ImportExportSpecification, i As Long, oldXML() As String, newXML As String
          
              Const newXlsxFileSpec = "C:\Users\Gord\Desktop\anotherTest.xlsx"  ' for testing
          
              Set ies = CurrentProject.ImportExportSpecifications("Import-xlsxTest")
              oldXML = Split(ies.XML, vbCrLf, -1, vbBinaryCompare)
              newXML = ""
              For i = 0 To UBound(oldXML)
                  If i = 1 Then  
                      ' re-write the second line of the existing XML
                      newXML = newXML & _
                              "<ImportExportSpecification Path = """ & _
                              newXlsxFileSpec & _
                              """ xmlns=""urn:www.microsoft.com/office/access/imexspec"">" & _
                              vbCrLf
                  Else
                      newXML = newXML & oldXML(i) & vbCrLf
                  End If
              Next
              ies.XML = newXML
              ies.Execute
              Set ies = Nothing
          End Sub
          

          有关ImportExportSpecification 对象的更多信息,请参阅

          ImportExportSpecification Object (Access)

          【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-09-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-02
          • 1970-01-01
          • 2021-08-07
          • 1970-01-01
          • 2015-05-06
          相关资源
          最近更新 更多