我很难确定如何将动态范围传递给公式。
通常,我会遇到一种情况,我知道我的范围将在哪一列中(以下示例),其中LR是我的范围中的行数。
Range("A1:A" & LR).FormulaR1C1 = ....some formula here
当我必须使用(在我的情况下)列标题名称动态创建范围时,问题就开始了。我可以通过“标题名称”找到该列,获取列号,将其转换为字母,但是我尝试过的任何解决方案都无效。
这是我用来获取列号的方法:
Function getColumn(searchText As String, wsname As String) As Integer
Set aCell = Sheets(wsname).Rows(1).Find(what:=searchText, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If aCell Is Nothing Then
MsgBox ("Column was not found. Check spelling")
Exit Function
Else
getColumn = aCell.Column
End If
End Function
我使用此代码将其转换为字母:
Function Col_Letter(lngCol As Long) As String
Dim vArr
vArr = Split(Cells(1, lngCol).Address(True, False), "$")
Col_Letter = vArr(0)
End Function
现在,要在该范围内填充公式,我尝试过类似的操作,但不幸的是没有运气:
colLetter = Col_Letter(manuallyAdjustedNumber)
Range(colLetter & "2:" & colLetter & LR).FormulaR1C1 = "=EXACT([RC-1],[" & harnessDrawingNumber & " - " & manuallyAdjustedNumber & "])"
我将不胜感激!谢谢!
答案 0 :(得分:4)
忘记更改字母,只需使用Cells
With Worksheets("Sheet1")
.Range(.Cells(2,manuallyAdjustedNumber),.Cells(LR,manuallyAdjustedNumber)).FormulaR1C1 = ...
End With
答案 1 :(得分:2)
您正在使此 方法过于复杂。为什么要使用R1C1表示法,同时又将所有内容从列字母来回转换为列号,这完全超出了我的理解。
您有2个问题:
它看起来应该像这样:
Public Function GetColumn(searchText As String, wsname As String) As Integer
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
With ws
If LCase$(.Name) = LCase$(wsname) Then
Dim header As Range
Set header = .Rows(1).Find(searchText, , xlValues, xlWhole, xlNext, False)
If Not header Is Nothing Then
GetColumn = header.Column
Exit Function
End If
MsgBox ("Column was not found. Check spelling")
Exit Function
End If
End With
Next
MsgBox "Worksheet '" & wsname & "' not found."
End Function