簡體   English   中英

有沒有辦法在 Workbook.Open 中動態更改或指定 excel 文件的位置?

[英]Is there a way to dynamically change or specify the location of an excel file in Workbook.Open?

我編寫代碼從另一個工作簿中提取信息並將其復制到我的活動工作簿中。

sub copydata
    
    Workbooks.Open "C:\User\abc.xlsx" 
    
    'test.xlsx is the active workbook, and abc.xlsx is the workbook data is being copied from
    Workbooks("abc.xlsx").Worsheets("Sheet1").Range("A1:A10"). Copy
    Workbooks("test.xlsx").Worsheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteValues
    
    Workbooks("abc.xlsx").Close SaveChange:=True
    
End Sub

如果此 Excel 表在另一台計算機上運行宏,則目錄將不同,文件名也必須保持不變。
有沒有辦法動態更改它,或者在通過按鈕啟動宏時設置它?

我相信它是這樣工作的,但我沒有測試它。

您可以使變量變暗以代替您正在使用的字符串。

dim path as string
path = (wherever you are pulling the path string data from)
Workbooks(path).Worksheets("Sheet1").Range("A1:A10").Copy

您實際上可以對引號中的任何部分執行此操作。 只需對變量進行調暗並使用值 dim sheet 填充它作為 sheet dim range1 as range range1 = range("A1:A10") sheet = worksheets("Sheet1") 應該允許您將所有部分作為變量。 所以下面的代碼可以工作 Workbooks(path).Worksheets(sheet).range(range1).copy

ThisWorkbook.path 可能對您非常有用。 希望這對我正在做的事情有意義,因為代碼不夠完整,無法進行測試。

Dim Path1 as string
Dim Path2 as string
Dim Answer as boolean
Path1 = "Old"
Path2 = "New"
if Answer = true then
workbooks(ThisWorkbook.Path &"\" & Path1 & "\Newfile.xlsm") 
else
workbooks(ThisWorkbook.Path &"\" & Path2 & "\Newfile.xlsm")
end if

此示例基於“Answer”的值將文件保存到一個或另一個路徑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM