【问题标题】:extract column range from formula in excel using macro使用宏从excel中的公式中提取列范围
【发布时间】:2016-10-27 09:48:35
【问题描述】:
Sub AddNameNewSheet1()
    Dim wsToCopy As Worksheet, wsNew As Worksheet
    Dim Newname As String
    Newname = InputBox("Number for new worksheet?")
    Set wsToCopy = ThisWorkbook.Sheets("Sheet1")
    Set wsNew = ThisWorkbook.Sheets.Add
    If Newname <> "" Then
        wsNew.Name = Newname
    End If
    wsToCopy.Cells.Copy wsNew.Cells
    Dim cell As Range
    Dim bIsNumeric As Boolean
    Dim testFormula As String
    bIsNumeric = False

    For Each cell In wsNew.Range("A1:M40")
        If cell.HasFormula() = True Then
           If bIsNumeric Then
                If testFormula = CStr(cell.Formula) Then
                    cell.Value = "<"
                Else
                    testFormula = cell.Formula
                    cell.Value = "F"
                End If
           Else
             testFormula = cell.Formula
             cell.Value = "F"
           End If
           bIsNumeric = True

        ElseIf IsNumeric(cell) = True Then
           bIsNumeric = False
           If Len(cell) > 0 Then
               cell.Value = "N"
           End If

        Else
           bIsNumeric = False
           cell.Value = "L"

        End If
    Next cell
End Sub

我想提取公式中应用的列和行。例如, 如果公式是 =SUM(A10:F10) 那么我想要 A10 和 F10 然后我删除那有没有办法找出来。

我的实际目的是找到没有列和行值的公式。 提前致谢。

【问题讨论】:

    标签: vba excel macros


    【解决方案1】:

    如果你想从公式中得到 A10 和 F10,你可以使用这个,将你的范围传递给strRange

    Sub Extract_Ranges_From_Formula()
    
    Dim strRange As String
    Dim rCell As Range
    Dim cellValue As String
    Dim openingParen As Integer
    Dim closingParen As Integer
    Dim colonParam As Integer
    Dim FirstValue As String
    Dim SecondValue As String
    
    
    strRange = "C2:C3"
    
    For Each rCell In Range(strRange)
    
        cellValue = rCell.Formula
    
        openingParen = InStr(cellValue, "(")
        colonParam = InStr(cellValue, ":")
        closingParen = InStr(cellValue, ")")
    
    
        FirstValue = Mid(cellValue, openingParen + 1, colonParam - openingParen - 1)
        SecondValue = Mid(cellValue, colonParam + 1, closingParen - colonParam - 1)
    
        Debug.Print FirstValue
        Debug.Print SecondValue
    
    Next rCell
    
    End Sub
    

    它对两个返回值进行Debug.Print

    【讨论】:

    • 但是没有固定的公式模式我想要任何类型的公式中的任意数量的范围。
    • 您需要遍历rCell.Formula 字符串并提取所有范围。您没有提供任何关于您正在搜索的公式的指示。如果您正在寻找没有范围的公式,那么您也可以这样做,使用相同的想法。
    • 谢谢哥们,我认为这是找出这一点的唯一方法,但有什么办法可以删除范围。还有一件事,公式不是静态的,它可以是任何东西。如果您有任何删除范围的想法,请建议我。我只想要没有范围的公式
    猜你喜欢
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    相关资源
    最近更新 更多