在IF公式中引用Workbook变量

时间:2017-07-26 14:43:08

标签: excel vba excel-vba

我有一个宏,它比较两个工作簿之间的数字,如果输出正确或不正确则输出。 其中一个工作簿存储为变量,因为它在上个月引用了它的名称。

Dim wb As Workbook
Set wb = Workbooks("Monthly Life Management Report " & Format(DateAdd("m", -1, Date), "mmmm yyyy") & ".xlsm")

运行宏的最后一部分时,我收到应用程序或对象定义错误。

 Range("E8").Select
ActiveCell.FormulaR1C1 = _
"=IF([wb]'2 Claims'!R8C5 =[Template.xlsx]Claims!R8C5,""Correct"",""Incorrect"")"

整个脚本

Sub Monthly_Life_Management()


Dim thisWb As Workbook
Set thisWb = ActiveWorkbook
Workbooks.Add
ActiveWorkbook.SaveAs Filename:=thisWb.Path & "\Validation_File_" & Format(Date, "dd mm yy") & ".xls"


Dim wb As Workbook
Set wb = Workbooks("Monthly Life Management Report " & Format(DateAdd("m", -1, Date), "mmmm yyyy") & ".xlsm")



'Claims Tab
 wb.Activate
 Sheets("2 Claims").Select

 Range("C2:C13").Select
 Application.CutCopyMode = False
 Selection.Copy
 Windows("Validation_File_" & Format(Date, "dd mm yy") & ".xls").Activate
 Range("C2").Select
 ActiveSheet.Paste

 wb.Activate
 Sheets("2 Claims").Select
 Range("D2:D13").Select
 Application.CutCopyMode = False
 Selection.Copy
 Windows("Validation_File_" & Format(Date, "dd mm yy") & ".xls").Activate
 Range("D2").Select
 ActiveSheet.Paste

 wb.Activate
 Sheets("2 Claims").Select
 Range("E7:G7").Select
 Application.CutCopyMode = False
 Selection.Copy
 Windows("Validation_File_" & Format(Date, "dd mm yy") & ".xls").Activate
 Range("E7").Select
 ActiveSheet.Paste

'Counts
 Range("E8").Select
 ActiveCell.FormulaR1C1 = _
"=IF('[wb]2 Claims'!R8C5 ='[Template.xlsx]Claims'!R8C5,""Correct"",""Incorrect"")"

 Cells.Select
 Selection.Copy
 Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False

End Sub

1 个答案:

答案 0 :(得分:1)

您需要调整工作簿参考中'的位置:

"=IF('[wb]2 Claims'!R8C5 =[Template.xlsx]Claims!R8C5,""Correct"",""Incorrect"")"

编辑:根据您的add'l代码,您有wb作为变量。试试这个

"=IF('[" & wb.Name & "]2 Claims'!R8C5 =[Template.xlsx]Claims!R8C5,""Correct"",""Incorrect"")"

(注意:您可能需要也可能不需要.Name