Excel VBA——从外部工作簿取数的5种方法(原创整理)
(2011-02-25 14:17:58)
Excel VBA——从外部工作簿取数的5种方法(原创整理) ======================================================= '1、循环单元格取数,效率最低,不可取,初学者易犯 '2、区域相等取数 '3、复制粘贴取数 '4、借助数组取数
——以上4种都需要打开外部工作簿 '5、宏表函数取数(不打开工作簿)
======================================================= Private Sub GetValueFromOpenedWorkbook() '打开工作簿取数
MyWorkbook As Workbook Dim MyArry As Variant
Set MyWorkbook = Application.Workbooks.Open(\Settings\\Administrator.DATACENTER3.000\\桌面\\我的工作表.xlsx\ '方法1:
' Dim i As Integer, j As Integer ' n2 = MyWorkbook.Sheets.Count ' For i = 7 To 56 ' For j = 4 To 10
' Sheets(\我的工作表\MyWorkbook.Sheets(\我的工作表\ ' Next j ' Next i
'方法2:
' ThisWorkbook.Sheets(\我的工作表\MyWorkbook.Sheets(\我的工作表\ '方法3:
' ThisWorkbook.Sheets(\我的工作表\ ' MyWorkbook.Sheets(\我的工作表\
Paste:=xlPasteValues '方法4:
MyArry = MyWorkbook.Sheets(\我的工作表\ ThisWorkbook.Sheets(\我的工作表\ MyWorkbook.Close SaveChanges:=False Set MyWorkbook = Nothing End Sub '方法5:
Sub GetValueFromClosedWorkbook() '不用打开工作簿取数
p = \桌面\ f = \我的工作表.xlsx\ s = \我的工作表\
Application.ScreenUpdating = False For r = 7 To 56 For c = 4 To 10
a = Cells(r, c).Address
Cells(r, c) = GetValue(p, f, s, a) Next c Next r
Application.ScreenUpdating = True End Sub
Private Function GetValue(path, file, sheet, ref) ' 从未打开的Excel文件中检索数据 Dim arg As String ' 确保该文件存在
If Right(path, 1) <> \ If Dir(path & file) = \ GetValue = \ Exit Function End If
' 创建变量
arg = \ Range(ref).Range(\ ' 执行XLM 宏
GetValue = ExecuteExcel4Macro(arg) End Function
相关推荐: