读取VBA中的文件path

我在VBA很新,并试图寻找这个问题,但没有运气。 我有一个工作簿,列出A1中的文件path,B1中的工作簿名称以及C1和D1中的选项卡名称。 我尝试编写一个macros,它将从单元格A1打开一个文件,然后设置刚刚从原始B1打开的工作簿,并在C1和D1中设置工作表名称。 然后在下面的一行,并循环的过程。 我想我除了定义variablespath/工作簿/工作表之外,还设法完成了大部分工作。 以下是我到目前为止所提出的。 会有人有任何build议吗? 提前致谢!

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 

试试这个。 看起来你可能会对variables的范围感到困惑。 看到我的代码如下:

 ' 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) 

首先,在使用范围时,最好总是限定其path。 所以首先是工作簿,然后是工作表。 您也可以使用已设置的工作表variables。

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

我希望这有助于澄清!