在我的工作PC上,我没有写系统驱动器(c)。
因此,我使用了桌面文件夹的properties
,并将其位置更改为另一个驱动器(d)。
从windows 10,我使用我的桌面从那个驱动器(d)类似于它在驱动器(c)。
Problem:我尝试使用vba代码在桌面上打开工作簿
Dim wb1 As Workbook: Set wb1 = Workbooks.Open(Environ("USERPROFILE") & "\Desktop\Query1.xls")
,但我犯了这个错误
Run-time error 1004:Sorry, we couldn't find C:\Users\Waleed\Desktop\Query1.xls. Is it possible it was moved, renamed or deleted?
我问这个问题,因为我在我的工作pc和我的笔记本电脑上交替使用excel文件(没有限制)。
而且,每次我更换机器时,都很难更改我的vba代码。
一如既往,谢谢你的帮助。
发布于 2022-02-13 08:40:22
使用vbscript SpecialFolders
。
Set objShell = Wscript.CreateObject("Wscript.Shell")
strPath = objShell.SpecialFolders("Desktop")
请参阅完整列表这里。
Function Desktop() As String
'returns the path to Desktop
Desktop = CreateObject("wscript.shell").specialfolders("desktop")
End Function
发布于 2022-02-13 08:29:47
不同驱动器上的桌面
把它放到子里
Sub DirDesktop()
Dim DeskTopPath As String: DeskTopPath = Environ("USERPROFILE") & "\Desktop\"
If Len(Dir(DeskTopPath, vbDirectory)) = 0 Then
DeskTopPath = Replace(DeskTopPath, "C", "D", , 1)
End If
Debug.Print DeskTopPath & "Query1.xls"
End Sub
使用函数获取它
Sub GetDeskTopTEST()
Dim DeskTopPath As String: DeskTopPath = GetDeskTop
Debug.Print DeskTopPath & "Query1.xls"
End Sub
Function GetDeskTop() As String
GesktopPath = Environ("USERPROFILE") & "\Desktop\"
If Len(Dir(GetDeskTop, vbDirectory)) = 0 Then
GetDeskTop = Replace(GetDeskTop, "C", "D", , 1)
End If
End Function
,这里有另一个想法,
您可以设置自己的环境变量。转到Windows Settings > About >
,向下滚动到Advanced Settings
,在底部单击Environment Variables
。单击上面的New
框,在Variable Name
框中使用DeskTop
,在Variable value
框中使用路径。如果在两台计算机上都这样做,则可以在这两台计算机上使用Environ("DeskTop")
访问文件夹。您必须重新启动Excel才能使其生效。
发布于 2022-02-13 07:50:46
如果它找到该文件,请执行检查,否则设置一个不同的路径。
https://stackoverflow.com/questions/71098670
复制相似问题