我需要让VBA在一系列单元格中放置一个特定的公式,以便创建一个矩阵,这个范围需要根据数据点的数量来改变大小。以下是我要做的一般概述。
Sub Input_Formulas()
'Dim Target_2 as String <= Name of sheet
'Dim Row_Limit1 as Long <= Number of Rows
'Dim Row_Limit2 as Long <= Number of Colums
'Dim Row_Count as Long <= Total number of rows aka. total number of data points
Range("C3").Select '<= This will stay the same in all sheets
ActiveCell.FormulaR1C1 = "=COUNTIFS(R21C18:R71C18,RC2,R21C22:R71C22,R2C)" '<= The formula will stay the same but I need the range to move based on the total number of rows
Selection.AutoFill Destination:=Range("C3:G3"), Type:=xlFillDefault '<= The destination range needs to change based on Row_Limit2
Range("C3:G3").Select '<= Also needs to change based on Row_Limit2
Selection.AutoFill Destination:=Range("C3:G16"), Type:=xlFillDefault '<= Needs to change based on Row_Limit1
End Sub
答案 0 :(得分:0)
查找第3行的最后一列
LstCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
查找B列的最后一行
LstRw = .Cells(.Rows.Count, "B").End(xlUp).Row
将范围从C3设置为Last Row&amp;最后一栏
Set Rng = .Range(.Cells(3, "C"), .Cells(LstRw, LstCol))
将公式放在该范围内
Rng = "=COUNTIFS($R$21:$R$71,$B3,$V$21:$V$71,C$2)"
Sub Button1_Click()
Dim sh As Worksheet
Dim LstCol As Long
Dim LstRw As Long
Dim Rng As Range
Dim S As String
Set sh = Sheets("Sheet1")
With sh
LstCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
LstRw = .Cells(.Rows.Count, "B").End(xlUp).Row
Set Rng = .Range(.Cells(3, "C"), .Cells(LstRw, LstCol))
Rng = "=COUNTIFS($R$21:$R$71,$B3,$V$21:$V$71,C$2)"
End With
End Sub