简体   繁体   中英

Excel 2010 VBA formula with variable messing up

I have this code:

LastLine = Range("C" & Rows.Count).End(xlUp).Row
LastLine = "C" & LastLine
Range(LastLine).Select
ActiveCell.FormulaR1C1 = "=SUM(R4C3:R[-1]C)"
Range("E13").FormulaR1C1 = "=if(R12C5 - " & LastLine & " <> 0,R12C5 - " & LastLine & ","""")"

everything works expect for the formula the outcome for that is

"=IF($E$12 - $Z:$Z <> 0,$E$12 - $Z:$Z,"")"

Can anyone see what I'm doing wrong? also when I try

LastLine = Range(LastLine).address

It gives me an error

The variable LastLine is not typed and you change its type throughout your code. First, it is a number (the number of the row), then you assign it text, the letter C combined with the row number, for example "C3". Next you use that in an R1C1 reference, where C3 means Column 3, so the row number from the first LastLine assignment will end up as the column in the formula.

Your code would be cleaner if your variables were dimmed to specific types and you would not mix A1 notation with R1C1.

Sub test()
Dim LastLine As Long
Dim LastLineCell As String

LastLine = Range("C" & Rows.Count).End(xlUp).Row
LastLineCell = "C" & LastLine
Range(LastLineCell).Select
ActiveCell.FormulaR1C1 = "=SUM(R4C3:R[-1]C)"
Range("E13").FormulaR1C1 = "=if(R12C5 - R" & LastLine & "C26 <> 0,R12C5 - R" & LastLine & "C26,"""")"
End Sub

由于您使用的是R1C1表示法,因此必须将CsomeRow转换为RsomeRowC3

Range("E13").FormulaR1C1 = "=if(R12C5 - R" & LastLine & "C3 <> 0,R12C5 - R" & LastLine & "C3,"""")"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM