获取表示字符串第一个实例的单元格的列地址 (VBA)
Getting Column Address of Cell Representing the First Instance of a String (VBA)
我想获取包含特定字符串的特定工作表中第一个单元格的列地址。
这是我为此编写的代码:
Dim StringInQuestion As String
Dim ColumnRange1 As Range
NamedSheet.Select
Range("A1").Select
On Error Resume Next
Set FinalCell = Cells(1, 1).SpecialCells(xlLastCell)
FinalCellAddress = Cells(FinalCell.Row, FinalCell.Column).Address
Range(ColumnRange1).Select
Selection.Copy
Set ColumnRange1 = NamedSheet.Cells
Dim ColumnRange2 As Range
ColumnRange2 = ColumnRange1.Find(StringInQuestion)
Dim ColumnComposite As Variant
ColumnComposite = ColumnRange1.Address(ColumnAbsolute:=True)
Dim Column As Variant
'Format column address procured for further use (remove any numbers)
Dim intColumn As Integer
ColumnComposite = Trim(ColumnComposite)
For intColumn = 1 To Len(ColumnComposite)
If Not IsNumeric(Mid(ColumnComposite, intColumn, 1)) Then
Column = Column & Mid(ColumnComposite, intColumn, 1)
End If
Next intColumn
'Column = Column
尽管此代码编译没有错误,但 'Column' 变量仍未定义。有任何想法吗?请分享。谢谢!
更新:
感谢@ScottHoltzman 的帮助。
有许多内置对象和方法可以使代码更简单:
Dim ws as Worksheet
Set ws = Worksheets("mySheet")
Dim rngFound as Range
Set rngFound = ws.Cells.Find(StringInQuestion, lookat:=xlPart) 'assumes can be part of cell, change to xlAll if need exact match
If not rngFound is Nothing Then
Dim sCol as String
sCol = Split(rngFound.Address,"$")(1) 'letter
'sCol = rngFound.Column 'to get number
Else
Msgbox StringInQuestion & " not found in " & ws.Name & "."
End If
我想获取包含特定字符串的特定工作表中第一个单元格的列地址。
这是我为此编写的代码:
Dim StringInQuestion As String
Dim ColumnRange1 As Range
NamedSheet.Select
Range("A1").Select
On Error Resume Next
Set FinalCell = Cells(1, 1).SpecialCells(xlLastCell)
FinalCellAddress = Cells(FinalCell.Row, FinalCell.Column).Address
Range(ColumnRange1).Select
Selection.Copy
Set ColumnRange1 = NamedSheet.Cells
Dim ColumnRange2 As Range
ColumnRange2 = ColumnRange1.Find(StringInQuestion)
Dim ColumnComposite As Variant
ColumnComposite = ColumnRange1.Address(ColumnAbsolute:=True)
Dim Column As Variant
'Format column address procured for further use (remove any numbers)
Dim intColumn As Integer
ColumnComposite = Trim(ColumnComposite)
For intColumn = 1 To Len(ColumnComposite)
If Not IsNumeric(Mid(ColumnComposite, intColumn, 1)) Then
Column = Column & Mid(ColumnComposite, intColumn, 1)
End If
Next intColumn
'Column = Column
尽管此代码编译没有错误,但 'Column' 变量仍未定义。有任何想法吗?请分享。谢谢!
更新:
感谢@ScottHoltzman 的帮助。
有许多内置对象和方法可以使代码更简单:
Dim ws as Worksheet
Set ws = Worksheets("mySheet")
Dim rngFound as Range
Set rngFound = ws.Cells.Find(StringInQuestion, lookat:=xlPart) 'assumes can be part of cell, change to xlAll if need exact match
If not rngFound is Nothing Then
Dim sCol as String
sCol = Split(rngFound.Address,"$")(1) 'letter
'sCol = rngFound.Column 'to get number
Else
Msgbox StringInQuestion & " not found in " & ws.Name & "."
End If