带回车的Range.Find()文本返回Excel VBA
我正在尝试做什么
find其标题单元格包含唯一string的列。 换句话说,我知道单元格的文本,而且我知道单元格在第1行,但是我不知道哪一列。 注:我想search整个文本,而不仅仅是其中的一部分。 注2:文本可能会有所不同,所以我无法将该值硬编码到我的代码中。 而是我需要使用存储值的variables 。
问题
newCol = Range("1:1").Find(headerText).Column
文本中没有回车时,简单的newCol = Range("1:1").Find(headerText).Column
工作正常 。 但是,如果有回车,这是行不通的。 它抛出错误“对象variables或块variables未设置”。 这是我的确切的标题string:
Incomplete Email (more text)
我已经试过了
我也试过使用WorksheetFunction.Match(headerText, Range("1:1"), 0)
,但得到了同样的问题。
其他说明和要求
这是一个加载项的一部分,所以我不想在用户的Excel表格中更改任何内容(如果我不需要)(即,我不想删除回车符)。
从技术上讲,我正在做一个函数:
Public Function getColumn(headerText As Variant) getColumn = Range("1:1").Find(headerText).Column End Function
谢谢!
请尝试下面的代码
Public Function getColumn(headerText As String) str1 = Split(headerText, vbCrLf) str2 = UBound(str1) b = Range("1:1").Find(str1(0) & Chr(10) & str1(1)).Column End Function
事情是这样的:有和没有换行符的文本不是相同的文本,因此.Find
失败。 你应该做的是模式查找。 我刚刚testing过这个,它的工作原理是,如果没有换行符,那么应该有一个空格:
Sub test() Dim rex As RegExp, ran As Range Dim col As Integer, headerText As String 'read you headerText here Set rex = New RegExp rex.Pattern = RegexIt(headerText) For Each ran In Range("1:1") If rex.test(ran.Text) Then col = ran.Column Exit For End If Next ran MsgBox col End Sub Function RegexIt(what As String) As String what = Replace(what, "(", "\(") what = Replace(what, ")", "\)") what = Replace(what, "[", "\[") what = Replace(what, "]", "\]") what = Replace(what, "<", "\<") what = Replace(what, ">", "\>") what = Replace(what, " ", "[\n ]?") what = Replace(what, vbCrLf, "[\n ]?") End Function
祝你好运!
编辑:引用到Microsoft VBScript正则expression式5.5需要
编辑2 :编辑variables使用。 说明:用variables空格/换行符replacevariables值中的空格,并使用转义括号进行模式匹配。
即使标题单元格包含回车符,您的代码也应该可以工作:
Sub FindColumnWithTextInRowOne() Dim headerText As String, newCol As Long headerText = "whatever" newCol = Range("1:1").Find(headerText).Column MsgBox newCol End Sub
这是因为您使用Find()不需要匹配单元格的全部内容。
编辑#1:
如果标题单元格是使用公式构造的,则应使用略有不同的Find()
:
Sub FindColumnWithTextInRowOne() Dim headerText As String, newCol As Long, r As Range headerText = Range("H1").Text newCol = Range("1:1").Find(What:=headerText, LookAt:=xlWhole, LookIn:=xlValues).Column MsgBox newCol End Sub