簡體   English   中英

Excel VBA:單元格引用

[英]Excel VBA: cell referencing

我在引用單元格時遇到問題,不知道是否存在解決方案。

使用VBA代碼,我使用以下語法將對不同單元格的引用寫入單元格:

activecell.formula = "=" & Cells(A1).address

現在,我需要為數千個單元格復制此公式。 每個單元格應引用一個順序cell (A1,A2,A3....A120..)

我的問題是使用

Cells(A1).address

它修復了Cells(A1) 使用自動填充功能時,我有成千上萬個單元格都引用同一cells(A1) ,而每次引用下一個cell (A2,A3,A4..)時,我都需要動態引用。 我需要使用自動填充功能,因為如果我使用loop和固定引用在每個單元格上編寫公式,則代碼將需要幾個小時才能運行(如前所述,有成千上萬個單元格)

然后,我應該使用相對參考格式:

activecell.formulaR1C1 = ...

但是單元格(A1)始終與我的活動單元格不在同一距離。

通過VBA,我可以計算每次與activecell ,但是如何使用R1C1表示法使用此數據?

所以,可以說使用

row.count

函數,我可以計算我要引用的第一個單元格,(這次)在第100行和第3列上。因此,我有:lastrow = 100,column =3。請注意,行100每次更改運行宏。 我的activecell cells(5,5)cells(5,5)

這是我想使用的:

Sub problemsolved ()

Dim lastrow as string
Dim RowL as string
Dim CoL as string

lastrow = activesheet.cells(rows.count, 1).End(xlUp).row


cells(5,5).select

Rol = lastrow - 5
Col = 3 -5


activecell.formulaR1C1 = "=R[Rol]C[Col]"

selection.autofill Destination:=Range(cells(5, 5), cells(10005, 5))

end sub

假設lastrow = 100,我需要得到以下結果:

cell(5,5): =cells(100,3)
cell(6,5): =cells(101,3)
cell(7,5): = cells(102,3)
.....
cell(10005,5): = cells(10100,3)

當然,我已經嘗試過語法:

activecell.formulaR1C1 = "=R[lastrow]C[3]"

但它不起作用,那我該怎么辦呢? 有人有主意嗎?

謝謝

采用:

With ActiveSheet
    .Range(.Cells(5,5),.Cells(10005,5)).FormulaR1C1 = "=R[" & RowL & "]C[" & col & "]"
End With 

無需自動填充

所以

Sub problemsolved ()

Dim lastrow as Long
Dim RowL as Long
Dim CoL as Long

lastrow = activesheet.cells(rows.count, 1).End(xlUp).row



Rowl = lastrow - 5
Col = 3 -5


With ActiveSheet
    .Range(.Cells(5,5),.Cells(10005,5)).FormulaR1C1 = "=R[" & RowL & "]C[" & col & "]"
End With 

end sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM