请注意,如果您Dim Purchasing_Document, Backup_Purchasing_Document As String
仅声明最后一个变量是 aString
而第一个变量是 a Variant
。在 VBA 中,您需要为每个变量指定一个类型:Dim Purchasing_Document As String, Backup_Purchasing_Document As String
.
Range.Find 方法的文档指出:
每次使用此方法时都会保存、LookIn
、LookAt
和SearchOrder
的设置。如果下次调用该方法时没有为这些参数指定值,则使用保存的值。 MatchByte
因此,如果使用Find
您至少应该指定这 4 个参数,否则您无法预测Find
这些参数使用的是哪个设置。
也LookAt:=xlWhole
有必要区分"Purchasing Document"
和"Backup Purchasing Document"
因为第一个是第二个的一部分。
所以至少要做到以下几点:
Public Function FindIndexCol(ByVal IndexRow As String, ByVal IndexCol As String) As String
Dim rngIndexCol As Range
Set rngIndexRow = Worksheets("sheet1").Range(IndexRow)
Dim rngIndexCol As Range
Set rngIndexCol = rngIndexRow.Find(What:=IndexCol, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByColumns, MatchByte:=False)
If Not rngIndexCol Is Nothing Then
FindIndexCol = Split(Cells(1, rngIndexCol.Column).Address, "$")(1)
Else
'output some error if nothing was found
MsgBox "Could not find '" & IndexCol & "' in '" & IndexRow & "'.", vbCritical
'or return some error at least
'FindIndexCol = "Column not found"
End If
End Function
Public Sub Test()
Dim Purchasing_Document As String, Backup_Purchasing_Document As String
Purchasing_Document = FindIndexCol("1:1", "Purchasing Document")
Backup_Purchasing_Document = FindIndexCol("1:1", "Backup Purchasing Document")
End Sub
请注意,FindIndexCol
仅sheet1
由于此行而有效
Set rngIndexRow = Worksheets("sheet1").Range(rngIndexRow)
因此,我建议通过使其更通用来使其更有用
Public Function FindIndexCol(ByVal rngIndexRow As Range, ByVal ColumnName As String) As String
Dim rngIndexCol As Range
Set rngIndexCol = rngIndexRow.Find(What:=ColumnName, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByColumns, MatchByte:=False)
If Not rngIndexCol Is Nothing Then
FindIndexCol = Split(rngIndexRow.Parent.Cells(1, rngIndexCol.Column).Address, "$")(1)
Else
'output some error if nothing was found
MsgBox "Could not find '" & ColumnName & "' in '" & rngIndexRow.Address(External:=True) & "'.", vbCritical
'or return some error at least
'FindIndexCol = "Column not found"
End If
End Function
Public Sub Test()
Dim Purchasing_Document As String, Backup_Purchasing_Document As String
With Worksheets("sheet1")
Purchasing_Document = FindIndexCol(.Rows(1), "Purchasing Document")
Backup_Purchasing_Document = FindIndexCol(.Rows(1), "Backup Purchasing Document")
End With
End Sub