1

我正在使用 DIR 函数将一组 excel 文件导入访问。然后我传递 DIR 的属性以使访问中的表的名称与 excel 文件相同。唯一的问题是我的名字中也有 xls 我该如何阻止它?

下面的代码:

Sub Sample2()
Const cstrFolder As String = "F:\TCB_HR_KPI\Data View\"
Dim strFile As String
Dim i As Long

strFile = Dir(cstrFolder & "*.xls")
If Len(strFile) = 0 Then
MsgBox "No Files Found"
Else
Do While Len(strFile) > 0
    Debug.Print cstrFolder & strFile

    DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
    strFile, cstrFolder & strFile, True

    i = i + 1
    strFile = Dir()
Loop
MsgBox i & " Files are imported"
End If
End Sub
4

3 回答 3

1

根据需要使用辅助功能将其剥离...

Function StripFileExt(FileName As String) As String
  Dim Pos As Long
  Pos = InStrRev(FileName, ".")
  If (Pos > 0) And (Pos > InStrRev(FileName, "\")) Then
    StripFileExt = Left$(FileName, Pos - 1)
  Else
    StripFileExt = FileName
  End If
End Function
于 2013-11-06T21:56:38.937 回答
1

使用拆分函数拆分“。”,并将该数组的第一个元素作为您的表名。

Split(strFile, ".")(0)

您可以将该结果存储在中间变量中。或者直接在TransferSpreadsheet语句中使用表达式。

DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
    Split(strFile, ".")(0), cstrFolder & strFile, True

Note: Based on your previous question, I assumed the workbook file names contain only a single dot: names from REPORT1.xls thru REPORT67.xls However if the file names you're dealing with this time can include more than one dot, my first suggestion is inappropriate.

In that case, you can still use an expression which includes Split(), but that expression would not be as simple.

Left(strFile, Len(strFile) - Len(Split(strFile, ".")(1)) -1)

Notice that approach would accommodate any of the other Excel file extensions in addition to .xls

于 2013-11-06T22:16:47.160 回答
0

你想要这个吗 ?

Sub Sample2() 
'
  Const cstrFolder As String = "F:\TCB_HR_KPI\Data View\"
'
  Dim i As Long, lng As Long
'
  Dim strExt As String, strFile As String, strTable As String
'
  strExt = ".xls"
  lng = Len(strExt)
  strFile = Dir(cstrFolder & "*" & strExt)
'
  If Len(strFile) = 0 Then
    MsgBox "No Files Found"
  Else
    Do While Len(strFile) > 0
      '
      ' Debug.Print cstrFolder & strFile
      '
      strTable = Left(strFile, Len(strFile) - lng)
      '
      DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
        strTable, cstrFolder & strFile, True

      i = i + 1
      strFile = Dir()
    Loop
    MsgBox i & " Files are imported"
  End If
'
End Sub

因此,像 Sample1.xls 这样的文件将作为表 Sample1 导入。

于 2013-11-06T21:55:31.683 回答