Excel 在公式中使用变量
我试图在一个简单的加法公式中使用变量。首先,我搜索第3行call“Jan Expense Hours”中的列标题,MsgBox ColL返回字母“I”,MsgBox ColL2返回字母“J”,两者都是正确的。lRow返回第55行,这也是正确的。虽然当我尝试将这些变量添加到Excel 在公式中使用变量,excel,vba,Excel,Vba,我试图在一个简单的加法公式中使用变量。首先,我搜索第3行call“Jan Expense Hours”中的列标题,MsgBox ColL返回字母“I”,MsgBox ColL2返回字母“J”,两者都是正确的。lRow返回第55行,这也是正确的。虽然当我尝试将这些变量添加到工作表(“Calcs”).Range(“F4:F”和lRow.Formula=“=SUM('Resource Details'!&[ColL]&4:&[ColL2]&4)”时,我在这行代码中遇到了应用程序定义或对象定义的错误。有
工作表(“Calcs”).Range(“F4:F”和lRow.Formula=“=SUM('Resource Details'!&[ColL]&4:&[ColL2]&4)”
时,我在这行代码中遇到了应用程序定义或对象定义的错误。有人知道我做错了什么吗?顺便说一句,我正在搜索列标题,因为列在不同的副本上会移动
完整程序:
Sub JanTotHrsFind()
Dim lRow As Long
Dim lCol As Long
Dim strSearch As String
Dim aCell As Range
Dim ColL As String
Dim ColL2 As String
Dim ColNo As Long
Sheets("Resource Details").Activate
'find the column
strSearch = "*Jan Expense Hours*"
Set aCell = Sheets("Resource Details").Rows(3).Find(What:=strSearch, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False)
'convert column number to letter
ColNo = aCell.Column
ColL = Split(Cells(, ColNo).Address, "$")(1)
ColL2 = Split(Cells(, (ColNo + 1)).Address, "$")(1) 'adds one more column to right
MsgBox ColL
MsgBox ColL2
lRow = Cells.Find(What:="SUBTOTAL*", _
After:=Range(ColL & "4"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row - 1 'minus 1 row to move above
MsgBox "Last Row: " & lRow
'formula for Jan Expense Hours + Jan Capital Hours
'Worksheets("Calcs").Range("F4:F" & lRow).Formula = "=SUM('Resource Details'!I4:J4)"
'Worksheets("Calcs").Range("F4:F" & lRow).Formula = "=SUM('Resource Details'![" & ColL & "]4:[" & ColL2 & "]4)"
Worksheets("Calcs").Range("F4:F" & lRow).Formula = "=SUM('Resource Details'! & [ColL] & 4: & [ColL2] & 4)"
End Sub
您不应该将变量写在括号内
因此:
请您尝试一下我上面更正的代码,看看它是如何运行的。我知道我只是有点走火入魔了。这就成功了。谢谢这在我身上也经常发生:)很高兴这有帮助。不客气。
Worksheets("Calcs").Range("F4:F" & lRow).Formula = "=SUM('Resource Details'!" & [ColL] & "4:" & [ColL2] & "4)"