我需要将以下代码更改为:
现在:
'in a loop with a being rownumber
CurrInvoiceNum = ws2.Range("B" & a).Value
必需:
' Transaction ID is the column name of B and the reason for the change is that it need not always be in B.
CurrInvoiceNum = ws2.Range("Transaction ID" & a).Value
我尝试过这样的细胞:
Cells.Find(What:="Transaction ID", LookAt:=xlWhole).Column )
但无法使用rownumber ..
谢谢,
答案 0 :(得分:2)
第一种方法 - 使用Application.Match
(更快):
Dim colNum
With ws2
colNum = Application.Match("Transaction ID", .Range("1:1"), 0)
If IsError(colNum) Then
MsgBox "Column with header 'Transaction ID' not found"
Exit Sub
End If
CurrInvoiceNum = .Cells(a, colNum).Value
End With
第二种方法 - 使用.Find
:
Dim rng As Range
With ws2
Set rng = .Range("1:1").Find(What:="Transaction ID", LookAt:=xlWhole)
If rng Is Nothing Then
MsgBox "Column with header 'Transaction ID' not found"
Exit Sub
End If
CurrInvoiceNum = .Cells(a, rng.Column).Value
End With
这两个apporaches都假定您的标题位于第一行:.Range("1:1")
答案 1 :(得分:0)
这假设列名在第一行:
Sub dural()
Set r = Rows(1).Find(What:="Transaction Id")
a = 7
CurrInvoiceNum = r.Offset(a - 1, 0).Value
End Sub