在VBA中读取文件路径

时间:2017-04-21 14:47:36

标签: excel vba excel-vba

我在VBA很新,并试图为此搜索问题,但没有运气。我有一个工作簿,列出A1中的文件路径,B1中的工作簿名称和C1&amp ;;中的选项卡名称。 D1。我正在尝试编写一个宏,它将从单元格A1打开一个文件,然后设置它刚从原始B1打开的工作簿,并在C1&中设置工作表名称。 D1。然后在下面的一行循环并循环该过程。我认为除了定义变量路径/工作簿/工作表之外,我设法完成了大部分工作。以下是我到目前为止所提出的建议。有人会有什么建议吗?提前致谢!

Dim Macro As Workbook
Set Macro = Workbooks("Macros.xlsb")
Workbooks.Open Range("A1")
Dim WBRange As Range
WBRange = Macro.Range("B1").Value
Dim ParRange As Range
Set ParRange = Macro.Range("C1").Value
Dim CurrentWB As Workbook
Set CurrentWB = WBRange
Dim CurrentWS As Worksheet
Set CurrentWS = ParRange

1 个答案:

答案 0 :(得分:1)

试试这个。看起来您可能对使用变量范围感到困惑。请参阅下面的代码:

' Use a better name than this for your variable
Dim Macro As Workbook
Set Macro = Workbooks("Macros.xlsb")

Dim NewWorkbook As Workbook
' Notice that I fully qualify my range reference here, and then specifically retrieve the value from the cell.
Set NewWorkbook = Workbooks.Open(ThisWorkbook.Sheets("Sheetname").Range("A1").Value)

' You dont retrieve the value here. You also don't specify the workbook/sheet the range is in.
' Workbooks.Open Range("A1")

Dim WBRange As Range
' You always have to use set when assigning a value to an object
' This was a mistake as well.
' Set WBRange = Macro.Range("B1").Value
Set WBRange = Macro.Range("B1")

Dim ParRange As Range
' This was my mistake and causes an error. See the fix below:
' Set ParRange = Macro.Range("C1").Value
Set ParRange = Macro.Range("C1")

Dim CurrentWB As Workbook
' Set CurrentWB = WBRange
' I think you mean this:
Set CurrentWB = Workbooks(WBRange.Value)

Dim CurrentWS As Worksheet
'Set CurrentWS = ParRange
' Use this instead
Set CurrentWS = CurrentWB.Sheets(ParRange.Value)

首先,在使用范围时,最好总是限定其路径。首先是工作簿,然后是工作表。您还可以使用已设置的工作表变量。

接下来,如果要从某个范围中检索值,则必须使用Range.Value。虽然Range的默认成员是Value,但您将遇到检索到错误成员的情况(例如,您可以检索Range本身)。此外,您不能通过引用没有限定符的名称来设置工作表等于工作表的名称。您可以使用该名称作为索引器。在上面的代码中,我使用工作簿的名称在Workbooks集合中找到它。工作表相同。

我希望这有助于澄清!