VBA代码用于引用单独的已关闭工作簿中的另一个工作表上的范围,并对引用的单元格执行操作

时间:2018-01-12 08:29:52

标签: excel vba excel-vba

这是我的代码片段

    answer = MsgBox("To get the December KPI values from the previous year folder click Yes, if you want to go to default path, click No and If you are not sure, click Cancel", vbYesNoCancel + vbQuestion, "User Specified Path")
    If answer = vbYes Then

        MyFile = Application.GetOpenFilename(FileFilter:="Excel Files,*.xl*;*.xm*")

        Set wkb = Workbooks.Open(MyFile, UpdateLinks:=0)

        'Searching for Month KPI values of previous year December


TryAgain: xName = InputBox("Enter sheet name to find in the workbook: )", "Sheet search")

        If xName = "" Or xName = False Then Exit Sub
        found = False

            On Error Resume Next
            Sheets(xName).Activate

            If ActiveSheet.Name = xName Then
            MsgBox ("Sheet Found")
            found = True

            For j = 3 To 17


                Wb.Sheets(Name).Cells(16, j).Formula = "=(R[-13]C-'" & MyFile & xName & "'!R[-13]C)/'" & MyFile & xName & "'!R[-13]C"
                Wb.Sheets(Name).Cells(17, j).Formula = "=(R[-13]C-'" & xName & "'!R[-13]C)/'" & xName & "'!R[-13]C"
                Wb.Sheets(Name).Cells(18, j).Formula = "=(R[-13]C-'" & xName & "'!R[-13]C)/'" & xName & "'!R[-13]C"
                Wb.Sheets(Name).Cells(19, j).Formula = "=(R[-13]C-'" & xName & "'!R[-13]C)/'" & xName & "'!R[-13]C"
                Wb.Sheets(Name).Cells(20, j).Formula = "=(R[-13]C-'" & xName & "'!R[-13]C)/'" & xName & "'!R[-13]C"
                Wb.Sheets(Name).Cells(21, j).Formula = "=R[-12]C -'" & xName & "'!R[-12]C"
                Wb.Sheets(Name).Cells(22, j).Formula = "=R[-9]C -'" & xName & "'!R[-9]C"
                Wb.Sheets(Name).Cells(23, j).Formula = "=IFERROR(((R[-9]C- '" & xName & "'!R[-9]C)/'" & xName & "'!R[-9]C),0)"

            Next j

            wkb.Close

            End If


           If found = False Then
            If MsgBox("Worksheet name does not exist, click OK to try again or Click Cancel to Exit", vbOKCancel) _
            = vbCancel Then Exit Sub
            GoTo TryAgain

            End If

我想在另一个名为Month KPI Dec16的文件夹中引用名为Group View_2016.xlsx的另一个工作簿中名为2016的工作表。 主要问题是TryAgain代码段中的for循环。我想在当前的工作表中执行以下操作:

Wb.Sheets(Name).Cells(16, j).Formula = "=(R[-13]C-'" & MyFile & xName & "'!R[-13]C)/'" & MyFile & xName & "'!R[-13]C"

通过参考源表中的单元格。我无法弄清楚如何调整这个特定的公式来让它参考表格。

这是通过编写上述代码在单元格中应用的结果公式:

=(C3-'E:\John\2016\[Group View_2016.xlsxMonth KPI Dec16]Group View_2016'!C3)/'E:\John\2016\[Group View_2016.xlsxMonth KPI Dec16]Group View_2016'!C3

而我需要它:

 =(C3-'E:\John\2016\[Group View_2016.xlsx]Month KPI Dec16'!C3)/'E:\John\2016\[Group View_2016.xlsx]Month KPI Dec16'!C3

需要删除最后一位]Group View_2016并将]转移到Month KPI Dec16之前。

有人可以帮我吗?谢谢

1 个答案:

答案 0 :(得分:1)

设置wkb对象后,您可以使用以下内容更改MyFile变量,这应该将其全部放入正确的格式:

MyFile = wkb.path & "\[" & wkb.name & "]"