【问题标题】:Matching String from an Array to a Range Excel VBA将数组中的字符串匹配到范围 Excel VBA
【发布时间】:2011-10-21 00:48:48
【问题描述】:

我有以下公共子:

Public Sub HowToSort()
Dim i As Long, j As Long, h As Long, curCell As Range, cellBelow(1 To 10) As Variant
Dim sortOrder(1 To 10), colIsString(1 To 10) As Variant

For i = 1 To hdrCount
    'Find location of a cell
    Set curCell = Application.WorksheetFunction.Match(headRow(i), Range("a1:z1"))    ' Eventually extend outwards?
    cellBelow(i) = curCell.Offset(0, 1).Value
    If IsNumeric(cellBelow(i)) = False Then
        colIsString(i) = True
        sortOrder(i) = Application.InputBox(prompt:="Alphabetical = 'True' or Reverse Alphabetical = 'False' sorting for " & headRow(i), Type:=4)
    ElseIf IsNumeric(cellBelow(i)) = True Then
        colIsString(i) = False
        sortOrder(i) = Application.InputBox(prompt:="Ascending = True or Descending = False for " & headRow(i), Type:=4)
    Else
        MsgBox ("Program does not recognize value contained in column" & headRow(i))
        End
    End If
Next i
End Sub

其中使用名为 headRow 的全局变量,其中包含工作表顶部标题行名称的字符串数组。我正在尝试使用匹配函数来查找表头所在单元格的地址:

Set curCell = Application.WorksheetFunction.Match(headRow(i), Range("a1:z1"))
cellBelow(i) = curCell.Offset(0, 1).Value

然后我想使用这个地址,将它向下偏移一个单元格以查找输入的数据类型,该数据将输入到数组colIsString中。但是,.Match 函数不起作用,引用了“类型不匹配”错误。我不知道这怎么可能?根据我之前的研究,.Match 命令似乎接受了一个范围,然后搜索该范围以匹配单元格值。我已经尝试了 .Match 命令的几个化身,但都没有成功。感谢您的想法...

H3lue

【问题讨论】:

    标签: string excel vba range match


    【解决方案1】:

    使用 Find() 代替:

    Set curCell = Range("a1:z1").Find(headRow(i), , xlValues, xlWhole)
    If Not curCell Is Nothing Then
        'found the header
        cellBelow(i) = curCell.Offset(0, 1).Value
        'etc etc
    Else
        MsgBox "Header '" & headRow(i) & "' not found!"
    End If
    

    sortOrder 和 colIsString 将在您的子退出后立即超出范围...

    【讨论】:

      猜你喜欢
      • 2011-10-10
      • 2017-01-28
      • 1970-01-01
      • 2013-06-06
      • 1970-01-01
      • 2010-12-05
      • 1970-01-01
      • 2019-06-04
      • 2019-01-06
      相关资源
      最近更新 更多