【问题标题】:How to find if the column exists in Excel through VBA如何通过VBA查找列是否存在于Excel中
【发布时间】:2017-05-24 12:00:44
【问题描述】:

我的 Excel 中有两行中的两个标题,我根据这些标题为每一行上传值。如果两个标题的组合已经可用,则该行中的值将更新。如果该组合不可用,将创建一个新列。
示例 Excel

如图所示,如果我再次找到第 2 列和 B 列的组合,我可以针对第 2 列和 B 列更新新行中的值。如果还有另一种标题组合,例如第 5 列和 B 列,那么它将创建一个新列。

使用 VBA 我只能检查一个列标题,但不能检查标题的组合。我使用了下面的代码。

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 

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    Find 不能用于查找分布在多个单元格中的值。我推荐这种代码。

    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 和 Caption2 是您要查找的两个列标题。代码的第一部分遍历所有列以找到该组合。如果找到它,它会将找到它的列传递给以下代码。如果不是,则传递下一个空白列的编号。

    第二部分采用该列号并对其进行操作。如果它是一个使用过的列,您可以在那里添加您的值。如果它是一个新列,它会添加两个标题,然后您可以在其中添加您的值。

    此代码假定您知道字幕的顺序。如果您需要接受 A + B 或 B + A,则必须在传递到 Do 循环中的下一列之前检查这两个值。

    【讨论】:

      猜你喜欢
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多