使用VBA映射Excel列

时间:2012-11-28 10:15:03

标签: excel vba excel-vba

我目前正在将列名映射到excel中的变量,然后在我的公式中使用变量用于新行,这是一个示例示例;

Dim posType as String

Cells.Find(What:="PositionType", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
    :=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False).Activate


posType = ActiveCell.EntireColumn.Address(False, False)
posType = Left(posType, InStr(1, posType, ":") - 1)


Sheets("sheet1").Range("A1").Select

ActiveCell.End(xlToRight).Select

ActiveCell.Offset(0, 1).Select
Selection.FormulaR1C1 = "PTH Size"

 ' PTH SIZE
Cells.Find(What:="PTH SIZE", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
    :=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False).Activate
    ActiveCell.Offset(1, 0).Select

Selection.Formula = _
  "=IF(" & posType & "2=""PTH""," & settlementDateQuantity & "2,0)"

pthSize = ActiveCell.EntireColumn.Address(False, False)
pthSize = Left(pthSize, InStr(1, pthSize, ":") - 1)
r = ActiveCell.Row

With Worksheets("sheet1").Range(pthSize & r)
    .AutoFill Destination:=Range(pthSize & r & ":" & pthSize & lastrow&)
End With

我导入的文件可以按照列的顺序每天更改,但是它们使用相同的名称,目前我使用find方法获取列,然后将字母保存到字符串并使用引用我的公式然而,使用查找和映射100列的过程非常慢......

我一直试图想出一个更好的方法来做到这一点,但不能想到更快的事情,任何人都可以通过提出一种可能更快的方式来帮助我吗?

我也在考虑将我的项目转移到EXCEL DNA,是否有人知道我的宏运行速度有多快?

由于

1 个答案:

答案 0 :(得分:1)

您正在选择并移动工作簿,而不仅仅是执行分配,这将减慢程序A LOT !!!

我做了某些更改,让您朝着正确的方向前进 - 试试这个: (注意:这很快,很脏,所以我可能在单元格引用中犯了一些错误,但它至少应该让你朝着更好的方向前进)

  Dim posType As String
  Dim SelectedCell As Range

  Set SelectedCell = Cells.Find(What:="PositionType", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
      :=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
      False, SearchFormat:=False)

  posType = Mid(SelectedCell.Address, 2, InStr(2, SelectedCell.Address, "$") - 2)

  Set SelectedCell = Sheets("sheet1").Range("A1").End(xlToRight).Offset(0, 1)
  SelectedCell.Value = "PTH Size"

   ' PTH SIZE
  Set SelectedCell = Cells.Find(What:="PTH SIZE", After:=SelectedCell, LookIn:=xlFormulas, _
  LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
      False, SearchFormat:=False).Offset(1, 0)

  SelectedCell.Formula = "=IF(" & posType & "2=""PTH""," & settlementDateQuantity & "2,0)"


  pthSize = Mid(SelectedCell.Address, 2, InStr(2, SelectedCell.Address, "$") - 2)
  r = SelectedCell.Row

  Worksheets("sheet1").Range(pthSize & r).AutoFill Destination:=Range(pthSize & r & ":" & pthSize & lastrow&)

再次注意,这仍然可以提高效率,但这是一种更有效的做事方式......