Excel VBA:我们可以按名称引用列吗?

时间:2015-06-04 02:03:54

标签: excel-vba vba excel

我想通过标题名称引用列。

目前列是第4列,标题名称是“首选项”。 该列由“是”或“否”组成

第5列标题是“原因” 只有当“首选项”栏为“否”时才会填写

我的代码是

Private Sub CommandButton1_Click()

Dim i As Integer
Dim MyWorksheetLastRow As Byte
Dim MyWorksheetLastColumn As Byte

MyWorksheetLastRow = Worksheets(1).Cells(Rows.Count, "A").End(xlUp).Row
MyWorksheetLastColumn = Worksheets(1).Cells(1, Columns.Count).End(xlToLeft).Column

Worksheets(1).Cells(1, MyWorksheetLastColumn + 1).Value = "Result"
For i = 2 To MyWorksheetLastRow
If Cells(i, 4).Value = "Yes" Then
Cells(i, MyWorksheetLastColumn + 1).Value = Cells(i, 4).Value
Else: Cells(i, MyWorksheetLastColumn + 1).Value = Cells(i, 5).Value
End If
Next i

End Sub

我想要的是代替Cell(i,4),我想通过列标题示例调用它:Cells(i,“Preference”)。 因为我不会在之前的“偏好”列号。我使用excel vba因为我必须处理20-30个类似的文件。

2 个答案:

答案 0 :(得分:3)

除了我的评论,如果你想直接做,你必须这样做:

cells(i,Application.WorksheetFunction.Match("Preference", Range("1:1"), 0)).

答案 1 :(得分:1)

这是一个查找X实例列的函数。我在那里放了一个子程序,以此为例。

Sub ColInstanceExample()
Dim MyColInstance As Long
MyColInstance = ColInstance("Preference", 2) 'Pass in what you are searching for and the instance you want to return the column number for
If MyColInstance = 0 Then
    MsgBox "Not Found"
Else
    MsgBox "Found at column: " & MyColInstance
End If
End Sub

Function ColInstance(HeadingString As String, InstanceNum As Long)
Dim ColNum As Long
On Error Resume Next
ColNum = 0
For X = 1 To InstanceNum
    ColNum = (Range("A1").Offset(0, ColNum).column) + Application.WorksheetFunction.Match(HeadingString, Range("A1").Offset(0, ColNum + 1).Resize(1, Columns.Count - (ColNum + 1)), 0)
Next
ColInstance = ColNum
End Function