【问题标题】:How to find and replace the column name?如何查找和替换列名?
【发布时间】:2022-07-23 19:08:39
【问题描述】:

我正在尝试查找和替换列名。

我只想在第一行循环,但我的代码循环了整个工作表。

Dim sht As Worksheet
Dim fndList As Variant
Dim rplcList As Variant
Dim x As Long
Dim data As Variant

Set sht = ActiveWorkbook.Worksheets("ERT")

fndList = Array("colon.", _
                "Selec:", _
                "Sele, _
                "Submi")
                
rplcList = Array("A", "A1", "S1", "D1")

With sht

    'Loop through each item in Array lists
    For x = LBound(fndList) To UBound(fndList)
        'Loop through each worksheet in ActiveWorkbook
        'For Each sht In ActiveWorkbook.Worksheets("Exp")
        sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
          lookat:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
          SearchFormat:=False, ReplaceFormat:=False
        'Next sht
    Next x
  
End With

我只想查找和替换从第一行 A1 到第一行末尾的数组值。

【问题讨论】:

  • VBA 帮助说明WorkSheet.Cells 属性:返回一个 Range 对象,该对象代表工作表上的所有单元格(不仅仅是当前正在使用的单元格。调用sht.Cells.Replace ...,其中sht 是一个工作表。将sht 改为引用Range
  • 好的,所以保留 sht 但声明一个用于替换这些列名的范围对象,例如Dim rng As Rangerng = sht.Range("A1:F1")。然后拨打rng.Replace ...

标签: excel vba


【解决方案1】:

请尝试下一个方法。它将尝试匹配第一行标题上的第一个数组元素,并将找到的元素替换为第二行中的相应字符串:

Sub ReplaceHeaders()
  Dim shT As Worksheet, lastCol As Long, fndList, rplcList, rngHd As Range, mtch, i As Long
  
  Set shT = ActiveWorkbook.Worksheets("Final Exclusion")
  lastCol = shT.cells(1, shT.Columns.count).End(xlToLeft).Column
  
  fndList = Array("Enter one or more MSOs or ESOs to be excluded.  Separate multiple values using a semicolon.", _
                "Select the datasets from which you wish to exclude these MSOs:", _
                "Select the reason code for the exclusion:", _
                "Submitter's CWSID")

 rplcList = Array("MSO", "SOCS", "Reason's", "Submitter")
 Set rngHd = shT.Range(shT.cells(1, 1), shT.cells(1, lastCol))
 For i = 0 To UBound(fndList)
    mtch = Application.match(fndList(i), rngHd, 0)
    If Not IsError(mtch) Then
        rngHd(1, mtch).Value = rplcList(i)
    End If
 Next i
End Sub

【讨论】:

  • 现在超级完美
【解决方案2】:

dict='old_name':'new_name'

new_df=df.rename(columns={'MSO':'mso', 'SOCS':'socs','KPI':'kpi','原因':'原因', '提交者':'提交者'}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 2018-12-31
    • 2013-07-18
    • 1970-01-01
    • 2020-01-10
    相关资源
    最近更新 更多