使用vba获取具有特定文本的单元格的列号

use*_*653 2 excel vba excel-vba

sccelhot的excel嗨我需要获取一个单元格的列,文本为ACTION.

我目前的代码如下.

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngDV As Range
Dim oldVal As String
Dim newVal As String
Dim actionColName As String
If Target.Count > 1 Then GoTo exitHandler

On Error Resume Next
Set rngDV = Cells.SpecialCells(xlCellTypeAllValidation)
On Error GoTo exitHandler

If rngDV Is Nothing Then GoTo exitHandler

If Intersect(Target, rngDV) Is Nothing Then
   'do nothing
Else
  Application.EnableEvents = False
  newVal = Target.Value
  Application.Undo
  oldVal = Target.Value
  Target.Value = newVal
  If Target.Column = 3 Then
    If oldVal = "" Then
      'do nothing
      Else
      If newVal = "" Then
      'do nothing
      Else
      Target.Value = oldVal _
        & "+ " & newVal
      End If
    End If
  End If
End If

exitHandler:
  Application.EnableEvents = True
End Sub
Run Code Online (Sandbox Code Playgroud)

在上面的代码中有一个如下条件If Target.Column = 3 Then

我没有用3对值进行硬编码,而是将这个逻辑应用于完整列, 该列在该列的一个单元格中包含值ACTION.

bre*_*tdj 6

使用a Find确定包含Action的(第一个)列

Sub GetAction()
Dim rng1 As Range
Set rng1 = ActiveSheet.UsedRange.Find("Action", , xlValues, xlWhole)
If Not rng1 Is Nothing Then
MsgBox "Found in column " & rng1.Column
Else
MsgBox "Not found", vbCritical
End If
End Sub
Run Code Online (Sandbox Code Playgroud)