0

我正在尝试做一个可以通过标题名称找到一列的宏,然后选择整个列并运行“文本到列”命令。
我已经根据列的当前位置记录了宏:

Sub TTC()

    Columns("A:A").Select 'text to column and format it as TEXT
    Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=False, OtherChar _
        :=" ", FieldInfo:=Array(1, 2), TrailingMinusNumbers:=True

    Columns("D:D").Select 'text to column and format it as GENERAL
    Selection.TextToColumns Destination:=Range("D1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=False, OtherChar _
        :=" ", FieldInfo:=Array(1, 1), TrailingMinusNumbers:=True

End Sub

我也有这个宏来查找列号:

Set txt = Sheet1.Cells(1, 1).EntireRow.Find(What:="Text", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)
 CT = txt.Column
Set val = Sheet1.Cells(1, 1).EntireRow.Find(What:="Value", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)
 CV = val.Column

如何结合这两个宏?

4

1 回答 1

1
  1. 您不应将val其用作变量名,因为它是保留字。
  2. 您应该避免使用Select,否则Selection这是一种不好的做法。
  3. 您应该使用Option Explicit并声明所有变量。

这应该让您了解如何组合这些命令:

Option Explicit

Public Sub TTC()
    'text to column and format it as TEXT
    Dim RangeTxt As Range
    Set RangeTxt = Sheet1.Cells(1, 1).EntireRow.Find(What:="Text", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)

    Columns(RangeTxt.Column).TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=False, OtherChar _
        :=" ", FieldInfo:=Array(1, 2), TrailingMinusNumbers:=True


    'text to column and format it as GENERAL
    Dim RangeVal As Range
    Set RangeVal = Sheet1.Cells(1, 1).EntireRow.Find(What:="Value", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)

    Columns(RangeVal.Column).TextToColumns Destination:=Range("D1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=False, OtherChar _
        :=" ", FieldInfo:=Array(1, 1), TrailingMinusNumbers:=True
End Sub
于 2017-12-15T10:00:30.243 回答