我正在尝试编写代码,提示用户输入.xlsx文件路径,然后打开该工作簿。最终,我希望VBA从正在打开的工作簿中复制数据。但是,我无法让VBA打开工作簿。
这是我的代码:
Sub Select_File_Or_Files_Mac()
Dim MyPath As String
Dim MyScript As String
Dim MyFiles As String
Dim MySplit As Variant
Dim N As Long
Dim Fname As String
Dim mybook As Workbook
On Error Resume Next
MyPath = MacScript("return (path to documents folder) as String")
'Or use MyPath = "Macintosh HD:Users:Ron:Desktop:TestFolder:"
' In the following statement, change true to false in the line "multiple
' selections allowed true" if you do not want to be able to select more
' than one file. Additionally, if you want to filter for multiple files, change
' {""com.microsoft.Excel.xls""} to
' {""com.microsoft.excel.xls"",""public.comma-separated-values-text""}
' if you want to filter on xls and csv files, for example.
MyScript = _
"set applescript's text item delimiters to "","" " & vbNewLine & _
"set theFiles to (choose file of type " & _
" {""org.openxmlformats.spreadsheetml.sheet""} " & _
"with prompt ""Please select a file or files"" default location alias """ & _
MyPath & """ multiple selections allowed true) as string" & vbNewLine & _
"set applescript's text item delimiters to """" " & vbNewLine & _
"return theFiles"
MyFiles = MacScript(MyScript)
On Error GoTo 0
If MyFiles <> "" Then
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
MySplit = Split(MyFiles, ",")
For N = LBound(MySplit) To UBound(MySplit)
' Get the file name only and test to see if it is open.
Fname = Right(MySplit(N), Len(MySplit(N)) - InStrRev(MySplit(N), Application.PathSeparator, , 1))
If bIsBookOpen(Fname) = False Then
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MySplit(N))
On Error GoTo 0
If Not mybook Is Nothing Then
MsgBox "You open this file : " & MySplit(N) & vbNewLine & _
"And after you press OK it will be closed" & vbNewLine & _
"without saving, replace this line with your own code."
mybook.Close SaveChanges:=False
End If
Else
MsgBox "We skipped this file : " & MySplit(N) & " because it Is already open."
End If
Next N
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End If
Cells(1, 1) = MyFiles
Set mybook = Workbooks.Open(MyFiles)
End Sub
Function bIsBookOpen(ByRef szBookName As String) As Boolean
' Contributed by Rob Bovey
On Error Resume Next
bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function
当我运行代码时,出现1004运行时错误,说明无法找到所有大写文件路径中的文件。这很奇怪,因为用户必须在弹出窗口中选择文件,因此文件必须在那里。我也有代码将文件路径写入电子表格中的单元格1,1。奇怪的是程序打印的文件路径具有正确的外壳作为实际文件路径,但错误是全部大写。我认为问题是unix区分大小写,我在OSX上运行它。为什么Excel将文件路径放在所有大写字母中?如果我将文件路径硬编码到Workbooks.Open(这里是直接文件路径)
,也会发生这种情况我正在使用我在https://msdn.microsoft.com/en-us/library/office/hh710200(v=office.14).aspx
找到的代码答案 0 :(得分:0)
这似乎缺失了
' Change drive/directory to MyPath.
ChDrive MyPath
ChDir MyPath