按名称查找列标题并在列标题下select所有数据(Excel-VBA)

这是我的第一篇文章…

我正在尝试创build一个macros来执行以下操作:

  1. 按名称search电子表格列标题。
  2. 从列标题中select所选列中的所有数据。
  3. 将数字存储为文本并转换为数字。

    • 转换为数字用于VLookup。

例如:

Visual Spreadsheet示例:

在这里输入图像说明

我在网上发现了以下代码:

With ActiveSheet.UsedRange Set c = .Find("Employee ID", LookIn:=xlValues) If Not c Is Nothing Then ActiveSheet.Range(c.Address).Offset(1, 0).Select End If End With 

但是,我仍然遇到一些问题,任何援助将不胜感激。

试试这个。 只需将要查找的所有列标题名称添加到集合中。 我假设你没有超过200列,如果你只是更新为i = 1到200节到一个更大的数字。

 Public Sub FindAndConvert() Dim i As Integer Dim lastRow As Long Dim myRng As Range Dim mycell As Range Dim MyColl As Collection Dim myIterator As Variant Set MyColl = New Collection MyColl.Add "Some Value" MyColl.Add "Another Value" lastRow = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row For i = 1 To 200 For Each myIterator In MyColl If Cells(1, i) = myIterator Then Set myRng = Range(Cells(2, i), Cells(lastRow, i)) For Each mycell In myRng mycell.Value = Val(mycell.Value) Next End If Next Next End Sub 

避免在所有单元格中循环是很好的。 如果数据集增长,macros可能变得太慢。 使用特殊单元格并粘贴乘以1的特殊操作是完成任务的有效方式。

这工作…

 Dim SelRange As Range Dim ColNum As Integer Dim CWS As Worksheet, TmpWS As Worksheet 'Find the column number where the column header is Set CWS = ActiveSheet ColNum = Application.WorksheetFunction.Match("Employee ID", CWS.Rows(1), 0) 'Set the column range to work with Set SelRange = CWS.Columns(ColNum) 'Add a worksheet to put '1' onto the clipboard, ensures no issues on activesheet Application.ScreenUpdating = False Application.DisplayAlerts = False Set TmpWS = ThisWorkbook.Worksheets.Add With TmpWS .Cells(1, 1) = 1 .Cells(1, 1).Copy End With 'Select none blank cells using special cells...much faster than looping through all cells Set SelRange = SelRange.SpecialCells(xlCellTypeConstants, 23) SelRange.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply TmpWS.Delete CWS.Select Application.DisplayAlerts = True Application.ScreenUpdating = True 

好的,这是实现你的目标的简短方法。 首先,find保存员工ID的列。 那么只需将整个列设置为数字而不是文本格式?

 With Worksheets(1) ' Change this sheet to the one you are using if not the first sheet Set c = .Find("Employee ID", LookIn:=xlValues) If Not c Is Nothing Then ' The column we want is c's Column. Columns(c.Column).NumberFormat = 0 End If End With 

添加一个暗淡的范围,你想要的:

 Dim MyRng, RngStart, RngEnd as Range 

然后改变:

 ActiveSheet.Range(c.Address).Offset(1, 0).Select 

到下面,以便find该列中的所有数据。

 set RngStart = ActiveSheet.Cells(1, c.column) set RngEnd = ActiveSheet.Cells(rows.count, c.column).end(xlup) set MyRng = ActiveSheet.Range(RngStart & ":" & RngEnd) 

现在你可以玩数据了。 如果你想粘贴这个格式为数字的地方:

 MyRng.copy Sheets("Wherever").Range("Wherever").pastespecial xlvalues 

如果要更改现在find的单元格的格式( 如何在Excel工作表中将列格式设置为数字格式? ),如果需要小数点,则使用“number”而不是“0”:

 MyRng.NumberFormat = "0" 

或新的目的地:

 Sheets("Wherever").Range("Wherever").NumberFormat = "0" 

一般格式与转换为数字的function完全匹配:

 MyRng.NumberFormat = "General" MyRng.Value = MyRng.Value