【问题标题】:Dynamic Range in VBAVBA 中的动态范围
【发布时间】:2019-04-06 01:46:58
【问题描述】:

我很难弄清楚如何将动态范围传递给公式。

通常我会有一个场景,我知道我的范围将在哪一列(下面的示例),其中 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 & "])"

我会感谢任何帮助!谢谢!

【问题讨论】:

  • 您能否确认您从 Col_Letter() 函数中获得了正确的字母值?
  • Debug.Print 该公式并尝试在工作表中使用它。这不是你想的那样。您的括号已关闭。

标签: excel vba dynamic range


【解决方案1】:

忘记换成字母,直接用Cells

 With Worksheets("Sheet1")
    .Range(.Cells(2,manuallyAdjustedNumber),.Cells(LR,manuallyAdjustedNumber)).FormulaR1C1 = ...
End With

【讨论】:

  • 谢谢,这正是我要找的!
【解决方案2】:

你让这种方式太复杂了。为什么您使用 R1C1 表示法,同时将所有内容从列字母到列号来回转换,这完全超出了我的理解。

你有两个问题:

  • 您始终使用 ActiveWorkbook(下面的示例明确说明了这一点)。
  • 您需要确保找到工作表

它应该看起来更像这样:

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

【讨论】:

  • @BigBen 你说得对,我没注意到。问题中没有足够的信息来确定它应该是什么。
  • 感谢您的反馈!我在代码的前面识别工作表,我只是想更具体一点,而不是在这里发布 900 行代码;-) 我的主要问题是根据标题识别正确的范围。
猜你喜欢
  • 2021-10-02
  • 2019-06-16
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-27
相关资源
最近更新 更多