Excelmacros:find列单元格而不激活它

我build立一个函数来查找列:

Function findColumn(NameSheet As String, ColName As String) findColumn = 0 Worksheets(NameSheet).Select Sheets(NameSheet).Range("A1").Select Do Until ActiveCell.Value = "" searchTerm = ActiveCell.Value If (LCase(ActiveCell.Value) = LCase(ColName)) Then findColumn = Mid(ActiveCell.Address, 2, 1) Exit Do End If ActiveCell.Offset(0, 1).Activate Loop End Function 

这个function起作用! 但它激活其他工作表,我不得不返回到前一张表。 结果不是无缝的,因为在函数search列地址的时候有一个表格转换的小故障。

有没有更好的方法来做到这一点? 因为我多次使用这种方法,而且我的合作伙伴在每次点击单元格时出现故障时都不满意。

请帮忙

这里有一个可能的方法,重要的是它不会改变你的工作簿的重点。 这将返回search项的列号,假设它在第一行,如果没有find,则返回0。 如果NameSheet无效,popup窗口会通知您,它将返回0。

 Function findColumn(NameSheet As String, ColName As String) As Long 'Add Error checking to see if sheet Exists On Error Resume Next Dim sheetTest As String 'Copy sheet name, just to see if the sheet is valid sheetTest = Sheets(NameSheet).Name 'Check if sheet was found. If Err.Number <> 0 Then MsgBox "Sheet does not exist" Exit Function End If 'Search the first column in the NameSheet for the ColName, and return 'the column number. findColumn = Sheets(NameSheet).Rows(1).Find(What:=ColName, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False).Column End Function 

这是一个function,将按照您的build议工作,我相信,因为它永远不会。 .Selects或。 .Selects正在search的工作表,同时带回所需的列字母。 它也不循环每个单元格,这可能是非常低效的。

此函数将返回列字母,而不是数字。 如果你想要的数字,请参阅上面的Daniel的代码。

 Function findColumn(NameSheet As String, ColName As String) With Worksheets(NameSheet) Dim myRng As Range Set myRng = .Rows(1).Find(ColName, lookat:=xlWhole) If Not myRng Is Nothing Then findColumn = Split(myRng.Address, "$")(1) Else findColumn = "Column Not Found" End If End With End Function