2016-06-29 36 views
-1

我想獲取特定工作表中包含特定字符串的第一個單元格的列地址。獲取表示字符串第一個實例的單元格的列地址(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 

儘管這段代碼編譯沒有錯誤,「列」變量仍然是不確定的。有任何想法嗎?請分享。謝謝!

更新:

謝謝@ScottHoltzman的幫助。

+0

你只是想返回的第一次一定的字符串出現在列字母(或數字)工作表中的單元格? –

+0

嗨@ScottHoltzman ---列字母。謝謝你的幫助。 – PBG

+0

你的代碼不工作嗎?你會得到錯誤(如果是的話,什麼錯誤和地點)? – BruceWayne

回答

2

有許多內置的對象和方法,可以使代碼更簡單:

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 
相關問題