从Excel文件获取数据的最快方法是什么?

时间:2018-12-17 07:35:15

标签: excel vba excel-vba import

我的任务是从数千个Excel文件中复制范围F1:F200,并将它们粘贴到目标文件夹中的相邻列中。该宏有效,但是打开每个文件大约需要5秒钟。

我考虑过“获取数据”查询功能,但我并不熟悉。我什至无法确定是否可以导入单个范围并将其粘贴到需要的地方。

还有其他加快过程的方法吗?

(我看到了这篇文章:Read Excel file without opening it and copy contents on column first blank cell,但是我不能再尝试12个小时了。我希望到那时,有人会告诉我它肯定更快或更慢了。)

编辑:我认为说“打开,复制和粘贴”足以说明该过程,但是最好向您展示:

Sub LoopThroughFiles()
Dim StrFile As String
Dim aBook As Workbook, DestSheet As Worksheet
Dim dest As Range
Dim CurDir As String
Dim diaFolder As FileDialog

Set DestSheet = ThisWorkbook.Sheets("data modified")


' Chose directory 
MsgBox "Select Folder"
' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
'FIX: how to make the current directory the default for diaFolder?
diaFolder.AllowMultiSelect = False
diaFolder.Show

'This captures the Folder pathname
CurDir = diaFolder.SelectedItems(1)

ChDir CurDir
'cleanup
Set diaFolder = Nothing

StrFile = Dir(CurDir & "\*.xls")    
Dim aCell As Range

Do While Len(StrFile) > 0

    ' First cell of destination range
    DestSheet.Range("T4").End(xlToRight).Offset(-3, 1).Select
    'Open a workbook
    Set aBook = Workbooks.Open(Filename:=StrFile, ReadOnly:=True)

    ' Copy from Column F and the Paste
    aBook.Sheets(1).Range("F1", Range("F65536").End(xlUp)).Copy 
    DestSheet.Paste

    ' Close the book
    aBook.Application.CutCopyMode = False
    aBook.Close SaveChanges:=False

    StrFile = Dir
Loop


MsgBox "Done"

2 个答案:

答案 0 :(得分:1)

这应该快一点

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim target As Range
Set target = DestSheet.Range("T4").End(xlToRight).Offset(-3, 1)

Do While Len(StrFile) > 0


    'Open a workbook
    Set aBook = Workbooks.Open(Filename:=StrFile, ReadOnly:=True)

    ' Copy from Column F and then Paste
    aBook.Sheets(1).Range("F1:F200").Copy
    target.PasteSpecial xlPasteAll

    ' Close the book
   ' aBook.Application.CutCopyMode = False 'not needed
    aBook.Close SaveChanges:=False
 Set target = target.Offset(0, 1) 'move pointer 1 column right
    StrFile = Dir
Loop

答案 1 :(得分:0)

这是使用oledb的方法。

const s = "haveaniceday";
let result = encryption(s);

function encryption(s) {

  let sqr = Math.sqrt(s.length),
    col = Math.ceil(sqr),
    row = Math.floor(sqr);

  let chunks = chunkSubstr(s, col);
  // => ["have", "anic", "eday"]
  console.log(chunks);

  for (var i = 0; i < chunks.length; i++) {
    // do some magic here...      
    // expected output: "hae and via ecy"
  }

}


function chunkSubstr(str, size) {
  const numChunks = Math.ceil(str.length / size)
  const chunks = new Array(numChunks)

  for (let i = 0, o = 0; i < numChunks; ++i, o += size) {
    chunks[i] = str.substr(o, size)
  }

  return chunks
}