| 在Microsoft Excel中,从封闭的工作簿中获取信息是使用VBA代码获取准确数据的最省时的方法之一。在本文中,我们将学习如何在Microsoft Excel中使用VBA从封闭的工作簿中读取信息。

如果要通过电子邮件或其他任何来源获取多个文件,并且想要获取存储在特定单元格中的信息,则应阅读本教程。

为了理解这个例子,我们需要在VBA代码中使用的路径中创建一些示例文件。在这里,我们在“ D:\ testing”路径中保存了两个文件(北和西文件)。

要从文件夹中的所有excel文件中提取数据,我们需要按照以下步骤启动VB编辑器:

单击“开发人员”选项卡。从“代码”组中选择“ Visual Basic”

img1

  • 将以下代码复制到标准模块中

Sub ReadDataFromAllWorkbooksInFolder()

Dim FolderName As String, wbName As String, r As Long, cValue As Variant

Dim wbList() As String, wbCount As Integer, i As Integer

FolderName = "D:\testing"

' create list of workbooks in foldername' --- Comment

wbCount = 0

wbName = Dir(FolderName & "\" & "*.xls")

While wbName <> ""

wbCount = wbCount + 1

ReDim Preserve wbList(1 To wbCount)

wbList(wbCount) = wbName

wbName = Dir

Wend

If wbCount = 0 Then Exit Sub

' get values from each workbook' --- Comment

r = 0

Workbooks.Add

For i = 1 To wbCount

r = r + 1

cValue = GetInfoFromClosedFile(FolderName, wbList(i), "Sheet1", "A1")

Cells(r, 1).Formula = wbList(i)

Cells(r, 2).Formula = cValue

Next i

End Sub

Private Function GetInfoFromClosedFile(ByVal wbPath As String, _

wbName As String, wsName As String, cellRef As String) As Variant

Dim arg As String

GetInfoFromClosedFile = ""

If Right(wbPath, 1) <> "\" Then wbPath = wbPath & "\"

If Dir(wbPath & "\" & wbName) = "" Then Exit Function

arg = "'" & wbPath & "[" & wbName & "]" & _

wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)

On Error Resume Next

GetInfoFromClosedFile = ExecuteExcel4Macro(arg)

End Function

img2

img3

我们需要运行宏&以下将是结果的快照:

img4

===

结论:使用上述代码,我们可以从特定单元格的封闭工作簿中获取数据。

注意:以单元格A1为例。如果要从任何其他单元格检索数据,则只需提及该单元格。

image 48

如果您喜欢我们的博客,请在Facebook上与您的朋友分享。您也可以在Twitter和Facebook上关注我们。

我们很高兴收到您的来信,请让我们知道我们如何改进,补充或创新我们的工作,并为您做得更好。写信给我们[email protected]