将VBA插入公式格式?

时间:2013-12-16 04:17:47

标签: excel vba excel-vba

关于如何在excel公式中格式化VBA的快速问题。当您将公式插入excel并且您想要从vba插入变量时,例如,如果b是一个字符串,您将使用" & b & "是正确的格式吗?为了说明问题,我有下面的代码,并尝试使用该格式,以及...我不知道为什么它不会工作,我得到一个(编译错误:预期:结束语句)。谁能告诉我哪里出错了?

Dim HrsSTD As String
Dim HrsSAT As String
Dim HrsSUN As String
Dim HrsSTWN As String
Dim sdFormula

HrsSTD = ActiveCell.Address
Selection.Offset(0, 1).Select
HrsSAT = ActiveCell.Address
Selection.Offset(0, 1).Select
HrsSUN = ActiveCell.Address
Selection.Offset(0, 1).Select
HrsSTWN = ActiveCell.Address

sdFormula = "=IF((" & Range(NamedRange).Cells(2, 1).Address & _
       "=""Please add a title"",0,VLOOKUP((" & Range(NamedRange).Cells(2, 1).Address & _
       ",'Tables (H)'!$H$2:$J$6,2,FALSE)* _
" & HrsSTD & "+VLOOKUP(" & Range(NamedRange).Cells(2, 1).Address & _
       ",'Tables (H)'!$H$2:$J$6,2,FALSE)* _
" & HrsSAT & "*1.25+VLOOKUP((" & Range(NamedRange).Cells(2, 1).Address & _
       ",'Tables (H)'!$H$2:$J$6,2,FALSE)*" & HrsSUN & "* _
1.5+VLOOKUP((" & Range(NamedRange).Cells(2, 1).Address & _
       ",'Tables (H)'!$H$2:$J$6,2,FALSE)*" & HrsSTWN & "*0.75)"

我输入excel的代码是:但我想将A13和I16(即所有相关引用)更改为VBA中的变量

=IF(A13="Please add a title",0,VLOOKUP(A13,'Tables (H)'!$H$2:$J$6,2,FALSE)*F16+VLOOKUP(A13,'Tables (H)'!$H$2:$J$6,2,FALSE)*G16*1.25+VLOOKUP(A13,'Tables (H)'!$H$2:$J$6,2,FALSE)*H16*1.5+VLOOKUP(A13,'Tables (H)'!$H$2:$J$6,2,FALSE)*I16*0.75)

1 个答案:

答案 0 :(得分:2)

这是你在尝试什么?我也看到你没有听从我之前的回答。

还有一个提示。打破简单部分的代码。它更容易理解。

您的代码存在问题

",'Tables (H)'!$H$2:$J$6,2,FALSE)* _
" & HrsSAT & "*1.25+VLOOKUP((" & Range(NamedRange).Cells(2, 1).Address & _

你不能这样写。第一行没有结尾"。你不能把它带到下一行。

这是你正在尝试的吗?

Dim sFormula As String
Dim sAddr As String

sAddr = Range(NamedRange).Cells(2, 1).Address

sFormula = "=IF(" & sAddr & _
           "=""Please add a title"",0,VLOOKUP(" & _
           sAddr & ",'Tables (H)'!$H$2:$J$6,2,FALSE)*F16+VLOOKUP(" & _
           sAddr & ",'Tables (H)'!$H$2:$J$6,2,FALSE)*G16*1.25+VLOOKUP(" & _
           ",'Tables (H)'!$H$2:$J$6,2,FALSE)*H16*1.5+VLOOKUP(" & _
           sAddr & ",'Tables (H)'!$H$2:$J$6,2,FALSE)*I16*0.75)"