简体   繁体   中英

How to find if the column exists in Excel through VBA

I have two headers in two rows in my excel based on which i upload values for each row. if the combination of two headers is already available, the values will be updated in that row. If that combination is not available a new column will be created.
Sample Excel
样本xls

As in the image, If i find Column 2 and Column B combination again i can update value in a new row against Column 2 and Column B. If there is another combination of headers say, Column 5 and column B, then it will create a new column.

Using VBA i am able to check only one column header but not the combination of the headers. i used the below code.

Set c=ws.Range("B2",ws.Cells(2,Columns.Count)).Find:=What(d,1)
IF c is Nothing Then
My code
Else`My Code End If 

Find can't be used to find values spread over several cells. I suggest this kind of code.

Private Sub FindMatchingColumn()
    ' 24 May 2017

    Dim Caption1, Caption2
    Dim Combination As String
    Dim Captions As String
    Dim C As Long

    Caption1 = "Column A"
    Caption2 = "Column 1"
    Combination = CStr(Caption1) & CStr(Caption2)

    With ActiveSheet
        Do
            C = C + 1
            Captions = CStr(.Cells(1, C).value) & CStr(.Cells(2, C).value)
            If StrComp(Captions, Combination, vbTextCompare) = 0 Then Exit Do
        Loop While Len(Captions)

        If Len(Captions) Then
            MsgBox "Column " & C & " has matching captions"
        Else
            MsgBox "No matching captions were found" & vbCr & _
                   "Write new captions to Column " & C
            .Cells(1, C).value = Caption1
            .Cells(2, C).value = Caption2
        End If
    End With
End Sub

Caption1 and Caption2 are the two column headers you are looking for. The first part of the code loops through all the columns to find that combination. If it is found it passes the column where it was found to the following code. If not, it passes the number of the next blank column.

The second part takes that column number and acts upon it. If it is a used column you can add your value there. If it is a new column it adds the two captions and then you can add your values in it.

This code presumes that you know the sequence of the captions. If you need to accept either A + B or B + A both values must be checked before passing to the next column in the Do loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM