将数据从 txt 复制到 excel [关闭]

问题描述 投票:0回答:0

文本文件中的示例数据

Module 6

Pressure angle 22

Helix angle 25

第一步:程序要求打开一个txt文件

第 2 步:编程将数据分成行和列

第 3 步:程序在当前工作表的 sheet1 的单元格 (A1:A10) 中给出的 txt 文件中搜索名称

第四步:将txt中b列的数据复制粘贴到当前工作表的sheet1的b列中,分别命名

Sub ImportTextData()
      
    'Declare variables
    Dim FilePath As String
    Dim FileName As String
    Dim Text As String
    Dim Rows() As String    
    Dim RowData() As String    
    Dim i As Long    
    Dim j As Long   
 
    'Get the file path and name
    FilePath = Application.GetOpenFilename("Text Files (*.txt), *.txt")
    If FilePath = "False" Then Exit Sub
    
    FileName = Dir(FilePath)
    'Open the text file and read the data
    Open FilePath For Input As #1
    Text = Input$(LOF(1), #1)
    Close #1
    
    'Split the data into rows and columns
    Rows = Split(Text, vbCrLf)
    
    For i = LBound(Rows) To UBound(Rows)
        RowData = Split(Rows(i), " ")
        For j = LBound(RowData) To UBound(RowData)
            RowData(j) = Trim(RowData(j))
        Next j
    
        Rows(i) = Join(RowData, vbTab)
    Next i
    
    'Search for names and copy data to Sheet1
    Dim Name As Range
    Dim NameCell As Range
    Dim DataCell As Range
    
    Set Name = ThisWorkbook.Sheets("Sheet1").Range("A1:A10")
    For Each NameCell In Name    
        For i = LBound(Rows) To UBound(Rows)    
           If InStr(Rows(i), NameCell.Value) > 0 Then
               Set DataCell = NameCell.Offset(0, 1)
               DataCell.Value = Split(Rows(i), vbTab)(1)
               Exit For    
            End If    
        Next i    
    Next NameCell
    
End Sub
excel vba text ms-word names
© www.soinside.com 2019 - 2024. All rights reserved.