gpt4 book ai didi

excel - VBA Excel 将文本文件复制到工作表

转载 作者:行者123 更新时间:2023-12-02 17:14:14 25 4
gpt4 key购买 nike

我正在尝试对文本文件中的特定列进行统计,我认为最好的方法可能是将文本文件中的所有内容复制到 Excel 工作表中,然后从那里开始计数(否则我需要尝试直接从 Excel 文件中只读取这一行)。这是我到目前为止所拥有的代码:

Dim filePath As String
Dim currentValue As String
Dim iRow As Long
Dim iCol As Long
Dim badAddress As Long
Dim coverageNoListing As Long
Dim activeListing As Long
Dim noCoverageNoListing As Long
Dim inactiveListing As Long
Dim fso As Object
Dim f As Object

'' filePath would include entire file name (picked from a browser button)
filePath = ActiveSheet.Range("B2").Text

'' Makes sure there isn't a sheet named "Temp_Text_File"
For Each testSheet In ActiveWorkbook.Worksheets
If testSheet.Name Like "Temp_Text_File" Then flag = True: Exit For
Next

'' If there is a sheet named "Temp_Text_File" it will be deleted
If flag = True Then
Application.DisplayAlerts = False
ActiveWorkbook.Sheets("Temp_Text_File").Delete
Application.DisplayAlerts = True
End If

'' Recreate sheet
Sheets.Add.Name = "Temp_Text_File"
'' Here I would want to copy everything (similar to manually doing "Ctrl+A" then "Ctrl+C") from the text file

'' Then paste into worksheet (similar to manually doing "Ctrl+V") within this created worksheet range("A1")

'' Delete at the end (user has no need for it)
Application.DisplayAlerts = False
ActiveWorkbook.Sheets("Temp_Text_File").Delete
Application.DisplayAlerts = True

谢谢,

杰西·斯莫瑟蒙

最佳答案

我正在做类似的事情,这是我的子项目:

我打开一个以 | 作为分隔符的 txt 文件。然后将工作表的内容复制到我的目标工作簿(全局变量)。然后我关闭包含原始 txt 文件的第一个工作簿而不保存。

Workbooks.OpenText 的代码基本上来自录制宏并根据我的需要进行调整。

Sub ImportTextFile(path As String)
Dim SheetName As String
Dim TMPWorkBook As Workbook
Dim FilePath As String
Dim TxtFilePath As String
Dim TxtFileName As String

Set WB = ThisWorkbook

SheetName = "Test_Result"
TxtFileName = path & "file.txt"

Workbooks.OpenText FileName:= _
TxtFileName _
, Origin:=437, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, Other:=True, OtherChar:="|", FieldInfo:=Array(Array(1, 1), _
Array(2, 1)), DecimalSeparator:=".", ThousandsSeparator:=",", _
TrailingMinusNumbers:=True

Set TMPWorkBook = ActiveWorkbook
TMPWorkBook.Sheets("file").Select
Cells.Select
Selection.Copy

ResultWB.Activate

ResultWB.Sheets(SheetName).Select
Range("A1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Cells.Select
Cells.EntireColumn.AutoFit
ActiveSheet.Range("A1").Select
TMPWorkBook.Close savechanges:=False

End Sub

关于excel - VBA Excel 将文本文件复制到工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5837628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com