以下代码工作正常但现在如果我想让它给同事我需要使用相对路径来获取代码中的工作簿:
Sub HELLO()
Dim x As Workbook
Sheets("Sheet1").Cells.Clear
'## Open both workbooks first:
Set x = Workbooks.Open("C:\Users\500722\Desktop\dashboard\Task.xls")
'Now, transfer values from x to y:
Sheet1.Cells(1, 1) = x.Sheets("Page 1").Range("A1")
With x.Sheets("Page 1").UsedRange
'Now, paste to y worksheet:
Sheet1.Range("A1").Resize( _
.Rows.Count, .Columns.Count) = .Value
End With
x.Close
End Sub
如果我使用了赠送Set x = Workbooks.Open("\Task.xls")
,我会收到错误消息,说明无法找到该路径。
答案 0 :(得分:6)
请改用:
Set x = Workbooks.Open(ThisWorkbook.Path & "\Task.xls")
答案 1 :(得分:3)
您问题的不同视图 - Macro Mans答案确实提供了相对于工作簿的路径。
您的示例代码引用了用户桌面,因此我猜测这可能是您之后的路径 - 相对于用户的路径。
'Special folders are : AllUsersDesktop, AllUsersStartMenu
'AllUsersPrograms, AllUsersStartup, Desktop, Favorites
'Fonts, MyDocuments, NetHood, PrintHood, Programs, Recent
'SendTo, StartMenu, Startup, Templates
Public Sub Test()
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
MsgBox oShell.SpecialFolders("Desktop")
End Sub
如果您搜索SpecialFolders VBA
,会有大量网站提供此信息。
http://www.rondebruin.nl/win/s3/win027.htm
https://bytes.com/topic/access/insights/933853-find-users-special-folders-such-desktop-my-documents