所以从@Rebekare对此的回答来看question https://superuser.com/questions/304103/opening-a-file-for-output-input-in-microsoft-visual-basic-on-mac-os-x这对我有用。
我转到了有问题的文件test.csv
并打开立即窗口并输入?ThisWorkbook.Path
并得到了HDD:Users:USER:Desktop
.
然后我使用了建议的这条路径的串联Application.PathSeparator
& 文件名,即
FilePath = "HDD:Users:USER:Desktop" & Application.PathSeparator & "test.csv"
这是一种有用的方法,因为您可以获得实际的文件路径语法,然后将路径分隔符决策交给Application
.
根据@Mat'sMug 的建议,我发现this https://www.ozgrid.com/forum/forum/help-forums/excel-general/99849-vba-path-to-external-hd-on-mac-and-win,这将打开文件对话框,您可以选择所需的文件的完整路径,该文件将通过消息框返回。
Sub PathofFile()
OpenFile = Application.GetOpenFilename()
MsgBox OpenFile
End Sub
在同一个链接中,建议使用Dir
函数来测试文件路径是否有效。如果有效,您将返回文件名,如果无效,您将收到一个错误,您可以使用该错误来确定下一步操作,例如如果该文件路径中存在“test.csv”,则以下命令将返回该文件。
MsgBox Dir("HDD:Users:USER:Desktop:test.csv")
如果您正在对该文件执行其他操作,您可能需要添加一个测试来首先使用 Microsoft 的是否打开文件 https://support.microsoft.com/en-za/help/291295/macro-code-to-check-whether-a-file-is-already-open功能。示例如下:
Sub Test
If Not IsFileOpen(FilePath) Then
Set wb = Workbooks.Open(FilePath)
End If
End Sub
Function IsFileOpen(filename As String)
Dim filenum As Integer, errnum As Integer
On Error Resume Next ' Turn error checking off.
filenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open filename For Input Lock Read As #filenum
Close filenum ' Close the file.
errnum = Err ' Save the error number that occurred.
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case errnum
' No error occurred.
' File is NOT already open by another user.
Case 0
IsFileOpen = False
' Error number for "Permission Denied."
' File is already opened by another user.
Case 70
IsFileOpen = True
' Another error occurred.
Case Else
Error errnum
End Select
End Function