在VBA中引用excel

时间:2018-01-11 19:38:09

标签: excel excel-vba vba

我正在尝试使用2个for循环,以便从不同的Excel中获取2个不同的信息。第一个for循环工作正常,没有任何问题。我希望第二个for循环用作源,一个不同excel的单元格(第一个for循环使用当前工作簿作为源单元格)。问题是excel更改的名称如路径(Scorecard " & JobNumber & ".xlsm')中所示。我是否需要创建新变量并将该变量定义为新excel的路径?或者有更好的方法来完成这项工作吗?基本上它应该在特定单元格中获取一条信息并将其填充到另一个excel(master excel)上。

Sub Narrative()

Dim JobNumber As String
Dim srcCell As String

Dim id As Integer

For id = 4 To 150
    srcCell = "C" & id

    JobNumber = Range(srcCell).Value

    Range("P" & id).Value = "=IFERROR('Y:\Public\QA Other\Scorecards\Scorecard " & JobNumber & ".xlsm'!TotalN, "" "")"
Next

For id = 4 To 150
    srcCell = "S" & id

    JobNumber = Range(srcCell).Value

    Range("R" & id).Value = "=IFERROR('Y:\Public\QA Other\Scorecards\Scorecard " & JobNumber & ".xlsm'!Analyst, "" "")"
Next

End Sub

2 个答案:

答案 0 :(得分:1)

如果要查找JobNumber变量以从其他工作簿中提取信息,则需要确定要调用Range方法的工作簿和工作表。它默认为活动工作簿和工作表。尝试将第二个for循环更改为:

For id = 4 To 150
    srcCell = "S" & id

    JobNumber = Workbooks(wbkName).Worksheets(shtName).Range(srcCell).Value

    Range("R" & id).Value = "=IFERROR('Y:\Public\QA Other\Scorecards\Scorecard " & JobNumber & ".xlsm'!Analyst, "" "")"
Next

其中wbkName是带有工作簿名称的字符串变量(可能是“Scorecard”& JobNumber&“。xlsm”),shtName是一个字符串变量,包含该工作簿中的工作表名称。

我建议为您正在使用的每个工作簿/工作表创建变量,并限定所有Range方法。

答案 1 :(得分:0)

根据您的评论,S列不包含作业编号,该列S只是包含范围名称Analyst的其他工作簿中的列,我相信您希望代码为:

Sub Narrative()

    Dim JobNumber As String
    Dim srcCell As String

    Dim id As Long

    For id = 4 To 150
        'Obtain the "job number" from column C of the master sheet
        srcCell = "C" & id
        JobNumber = Range(srcCell).Value
        'Create formulas in column P and R to retrieve values from the 
        'individual job workbooks
        Range("P" & id).Value = "=IFERROR('Y:\Public\QA Other\Scorecards\Scorecard " & JobNumber & ".xlsm'!TotalN, "" "")"
        Range("R" & id).Value = "=IFERROR('Y:\Public\QA Other\Scorecards\Scorecard " & JobNumber & ".xlsm'!Analyst, "" "")"
    Next

End Sub

如果你真的想要有两个循环(并且确实没有必要这样做!)那么你仍然需要从主表的C列获得作业号,即

Sub Narrative()

    Dim JobNumber As String
    Dim srcCell As String

    Dim id As Long

    For id = 4 To 150
        'Obtain the "job number" from column C of the master sheet
        srcCell = "C" & id
        JobNumber = Range(srcCell).Value
        'Create formula in column P to retrieve value from the 
        'individual job workbooks
        Range("P" & id).Value = "=IFERROR('Y:\Public\QA Other\Scorecards\Scorecard " & JobNumber & ".xlsm'!TotalN, "" "")"
    Next
    For id = 4 To 150
        'Obtain the "job number" from column C of the master sheet
        srcCell = "C" & id
        JobNumber = Range(srcCell).Value
        'Create formula in column R to retrieve value from the 
        'individual job workbooks
        Range("R" & id).Value = "=IFERROR('Y:\Public\QA Other\Scorecards\Scorecard " & JobNumber & ".xlsm'!Analyst, "" "")"
    Next

End Sub