我有一个名为 SO2PO.csv 的 csv 文件,它的名称总是相同。它具有我导入到名为 PO 数据的 Excel 表中的数据,位于名为 Open Order 的工作簿中。我需要找到一种方法将 SO2PO.csv 中的所有数据导入 Open Order.xlsm 表 PO 数据。
我知道这是可能的,但如何?有人可以指出我正确的方向吗?
或者有没有办法让我可以导入任何放在特定文件夹中的 .csv 文件?
添加此代码以在 PO 数据表中创建一个 QueryTable 到您的数据源
创建 QueryTable 后,您只需右键单击刷新数据(或在打开时刷新)
Sub CSV_Import()
Dim ws As Worksheet, strFile As String
Set ws = ActiveWorkbook.Sheets("PO Data") 'set to current worksheet name
strFile = Application.GetOpenFilename("Text Files (*.csv),*.csv", , "Please select text file...")
With ws.QueryTables.Add(Connection:="TEXT;" & strFile, Destination:=ws.Range("A1"))
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.Refresh
End With
End Sub
如果您要使用查询表,请确保在之后进行清理,剩余的查询表在下游流程中让我有些头疼。
' get the file to the data sheet
Set ws = ActiveWorkbook.Sheets("Data")
With ws.QueryTables.Add(Connection:="TEXT;" & "mydata.csv", Destination:=ws.Range("A1"))
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.Refresh
End With
' delete the querytable if there is one
On Error GoTo nothingtodelete
Sheets("Data").QueryTables(1).SaveData = False
Sheets("Data").QueryTables.Item(1).Delete
nothingtodelete:
有可能的。
如果没有 vba,您将使用 DATA-Tab 并从文本源导入。
使用 vba,您可以将 csv 作为新工作簿打开:
Public Function openSource(fileToOpen As String) As Excel.Workbook
On Error GoTo err_exit
Dim f As Object
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
Set openSource = Nothing
If fs.fileexists(fileToOpen) Then
Set f = fs.GetFile(fileToOpen)
Set openSource = ThisWorkbook.Application.Workbooks.Open( _
FileName:=f.path, _
UpdateLinks:=2, _
ReadOnly:=True, _
AddToMRu:=False, _
Notify:=False)
Windows(openSource.Name).Visible = False
End If
Exit Function
err_exit:
'throwErrMsg "Failed to read File!", "openSource"
If Not openSource Is Nothing Then
openSource.Close SaveChanges:=False, RouteWorkbook:=False
End If
End Function
Dim CSVWorkbook As New Excel.Workbook
Set CSVWorkbook = openSource(c:\SO2PO.csv)
现在您可以像其他任何工作簿一样浏览此工作簿并复制行、列或整个工作表;)希望这会有所帮助。
另一种方法是在 vba 版本中使用从文本导入,但我现在没有示例。
有很多方法可以将数据导入 Excel。查询表(由 The_Barman 演示)、SQL、导入向导等。
通常,该方法取决于您需要导入的文件上的数据显示的干净程度,以及您是否确切知道数据的布局方式。例如,如果有空行、混合数据类型、合并单元格等,那么它可能是一场噩梦。
下面是一种较慢的“蛮力”方法,通常首先在 Excel 中打开文件来获取所有数据。当其他方法失败时,这通常是最后要做的事情。
Option Explicit
Public Sub ImportData()
Dim CSVFilename As String
Dim writeToFilename As String
Dim writeToSheet As String
Dim readXL As Workbook
Dim readWS As Worksheet
Dim writeXL As Workbook
Dim writeWS As Worksheet
Dim UsedRng As Range
CSVFilename = Environ$("USERPROFILE") & "\Desktop" & "\SO2PO.csv"
writeToFilename = Environ$("USERPROFILE") & "\Desktop" & "\Open Order.xlsx"
writeToSheet = "PO Data"
Set writeXL = GetObject(writeToFilename)
Set writeWS = writeXL.Sheets(writeToSheet)
'writeWS.Parent.Windows(1).Visible = True
Set readXL = GetObject(CSVFilename)
With readXL
Set readWS = readXL.Sheets(1)
Set UsedRng = RealUsedRange(readWS)
writeWS.Range(UsedRng.Address).Value = UsedRng.Value
End With
'close CSV without saving
readXL.Close SaveChanges:=False
Set readWS = Nothing
Set readXL = Nothing
'close template with save
writeXL.Close SaveChanges:=True
Set writeWS = Nothing
Set writeXL = Nothing
End Sub
Public Function RealUsedRange(ByVal WS As Worksheet) As Range
'Find used range
Dim FirstRow As Long
Dim LastRow As Long
Dim FirstColumn As Integer
Dim LastColumn As Integer
On Error Resume Next
With WS
FirstRow = .Cells.Find(What:="*", After:=.Cells(.Rows.Count, .Columns.Count), LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext).Row
FirstColumn = .Cells.Find(What:="*", After:=.Cells(.Rows.Count, .Columns.Count), LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext).Column
LastRow = .Cells.Find(What:="*", After:=.Range("A1"), LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastColumn = .Cells.Find(What:="*", After:=.Range("A1"), LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Set RealUsedRange = .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn))
End With
On Error GoTo 0
End Function
Sub demo()
Dim FilePath As String
FilePath = "C:\Users\Tamil\Desktop\padding_values.csv"
Open "C:\Users\Tamil\Desktop\padding_values.csv" For Input As #1
row_number = 0
Do Until EOF(1)
Line Input #1, LineFromFile
LineItems = Split(LineFromFile, ",")
ActiveCell.Offset(row_number, 0).Value = LineItems(2)
ActiveCell.Offset(row_number, 1).Value = LineItems(1)
ActiveCell.Offset(row_number, 2).Value = LineItems(0)
row_number = row_number + 1
Loop
Close #1
End Sub