这可能会让你继续前进。不得不做一次类似的事情。
步骤:
- 打开一个 Excel 工作表。
- 按 ALT-F11。
- 从菜单中选择“添加”。
- 从下拉列表中选择“模块”。
- 将下面的源代码复制到新创建的模块中。
- 更改 Public Const 声明背后的值以满足您的需要
- 运行调用导入
模块简述:
FindRow - 在表格中搜索关键字并返回找到关键字的单元格对象。
IsAnArry - 测试参数是否为数组类型。
CallImport - 开始导入的主子例程。
ImportEngineeringTextFile - 处理实际的导入和数据操作。
您唯一需要更改的是每个 Public Const 声明背后的值以满足您的需要,然后运行 CallImport。在下面的代码中,我添加了一些注释以帮助理解那里发生了什么。
Public Const MY_IMPORT_TABLE_COLUMNS As String = "A:F"
Public Const FULL_PATH_TO_IMPORT_FILE_NAME As String = "Map1.txt"
Public Const COLUMS_WHERE_TO_DELETE_SLASH As String = "D:D"
Public Const COLUMNS_TO_DELETE_WHEN_DONE As String = "A:B"
Public Const DESTINATION_CELL_FOR_DATA As String = "A1"
Public Const FIRST_COLUMN_OF_MY_TABLE As String = "A:A"
Public Const KEYWORDS_1 As Variant = "[keyword1]"
Public Const KEYWORDS_2 As Variant = "[keyword3]"
'You can add more keyword declarations if need be.
'If you do so, don't forget to change the call to ImportEngineeringTextFile
'in CallImport
Function FindRow(What As Variant) As Object
With ActiveSheet.Range(MY_IMPORT_TABLE_COLUMNS)
Set FindRow = .Find(What, After:=.Cells(.Rows.Count, .Columns.Count), LookIn:=xlValues, MatchCase:=False, LookAt:=xlWhole)
End With
End Function
Function IsAnArray(VAR As Variant) As Boolean
Dim I As Long
On Error Resume Next
I = VAR.Rows.Count
IsAnArray = ((VarType(VAR) > vbArray Or InStr(TypeName(VAR), "()") < 1) And Err.Number <> 0)
End Function
Sub CallImport()
Call ImportEngineeringTextFile(Array(KEYWORDS_1, KEYWORDS_2)) ' Add other keyword constants to the array if need be.
End Sub
Sub ImportEngineeringTextFile(ByVal KeyWords As Variant)
Dim KWord As Variant, Obj As Object, ValidRows() As Variant, I As Long, R As Variant
If Not IsAnArray(KeyWords) Then Exit Sub ' If the import parameter is not of type Array, do not continue.
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & FULL_PATH_TO_IMPORT_FILE_NAME, Destination:=Range(DESTINATION_CELL_FOR_DATA))
.Name = "Map1"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells ' This makes sure you can import over and over again with the same paramters, without cleaning the sheet first
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True ' Automatically adjust width of column after import
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False ' Do not ask for a filename
.TextFilePlatform = 850 ' Data in file is of code page IMB850 (ANSI)
.TextFileStartRow = 1 ' Import as from row 1
.TextFileParseType = xlDelimited ' This indacates a delimited fields file in stead of fixed field length file
.TextFileTextQualifier = xlTextQualifierDoubleQuote ' This indactes that data starting with double quote is considered to be text
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = True ' Fields can be seperated by tab character
.TextFileSemicolonDelimiter = False ' Fields can not be separated by semi-colon
.TextFileCommaDelimiter = False ' Fields can not be separated by comma
.TextFileSpaceDelimiter = True ' Fields can be separated by a space
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1) ' Data types of imported fields, need no changing since they are all set to automatic detection
.TextFileTrailingMinusNumbers = True ' Negative values can have trailing a negation sign
.Refresh BackgroundQuery:=False
End With
Columns(COLUMS_WHERE_TO_DELETE_SLASH).Select
Selection.Replace What:="/", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Range(DESTINATION_CELL_FOR_DATA).Select
I = 0
ReDim ValidRows(I)
Set ValidRows(0) = Nothing
For Each KWord In KeyWords ' Search for and store the rows where the keywords are found
Set Obj = FindRow(KWord)
If Not Obj Is Nothing Then ' A row was found containing a keyword
ReDim Preserve ValidRows(I) ' Allocate more space for the resulting array
Set ValidRows(I) = Obj
I = I + 1
End If
Next
For Each Obj In Range(FIRST_COLUMN_OF_MY_TABLE) ' Walk through the data table and delete all rows that do not contain one of the specified keywords
If Obj.Value = "" Then Exit For
I = 0
For Each R In ValidRows
If Obj.Row = R.Row Then
I = 1
Exit For
End If
Next
If I = 0 Then Obj.EntireRow.Delete Shift:=xlUp ' Delete a row
Next
Columns(COLUMNS_TO_DELETE_WHEN_DONE).EntireColumn.Delete Shift:=xlLeft ' Delete those columns you do not want to keep in the data table
End Sub