在本文中,我们将学习如何根据特定的定义条件从活动工作簿中的外部工作簿获取数据。

在此示例中,我们希望基于银行类别的名称和类型获取特定人员的货币详细信息。资金明细存储在“数据文件”工作簿中。

DataFile

在此示例中,我们编写了VBA过程“ ReadFormatting”,该过程返回付款明细以及格式样式。

逻辑解释

“ ReadFormatting”过程将范围对象作为输入,并在已定义范围对象旁边的单元格中返回输出。

它检查“数据文件”工作簿第一行中范围内的定义值,并找到列号。它检查“数据文件”工作簿的第一列中已定义范围的上一列的单元格的值,并找到行号。

找到可能匹配的列号和行号后,将返回具有找到的列号和行号的单元格的值以及格式样式。

可以使用其他过程或事件来运行“ ReadFormatting”过程。

我们将以两种方式运行“ ReadFormatting”过程:-。使用程序。使用工作表更改事件

使用过程

我们使用“ CallingProcedure”过程以单元格N13作为范围对象来调用“ ReadFormatting”过程。它将检查外部工作簿第一行中单元格N13中的值以查找列号,并检查外部工作簿第一列中单元格M13中的值以查找行号。找到列号和行号后,它将返回值以及格式样式。

ArrowRunningMacro

使用工作表更改事件

要添加工作表更改事件,请按照下列步骤操作:-。在Visual Basic编辑器中单击工作表名称,以激活工作表模块。

ArrowWritingWorksheetEvent

。单击代码窗口顶部左侧组合框中的工作表。

ArrowWorksheetChangeEvent

。单击代码窗口顶部右侧组合框中的更改。

我们已经使用工作表更改事件来运行该过程。当工作簿中任何单元格的值更改时,将触发工作表更改事件。使用IF语句,我们将change事件限制为仅在I列的单元格中的值更改时才触发。值已更改的单元格用作“ ReadFormatting”过程的输入。

请遵循以下代码

Option Explicit

Sub CallingProcedure()

'Calling procedure ReadFormatting for cell N13

Call ReadFormatting(Range("N13"))



End Sub

Sub ReadFormatting(rng As Range)

Dim varRow, varCol As Long

Application.ScreenUpdating = False

'Activating workbook "Data file.xlsx"

Workbooks("Data file.xlsx").Activate

'Checking for Errors

'If any runtime error occur then it will the pointer to end of the procedure

On Error GoTo Last

'Finding the column no after matching rng value in the first row of "Data file.xlsx" workbook

varRow = Application.Match(rng.Value, Rows(1), 0)

'Offset method is used for moving one cell in the previous column

'Finding the row no after matching value of cell in the first column of "Data file.xlsx" workbook

varCol = Application.Match(rng.Offset(0, -1).Value, Columns(1), 0)

'Using If statement for checking errors

'If error not found in varRow and varCol then execute below code

If Not IsError(varRow) And Not IsError(varCol) Then

'Copying value of cell where match of row and column intersect

Cells(varCol, varRow).Copy



'Pasting the format of copied cell

rng.Offset(0, 1).PasteSpecial xlPasteFormats



'Pasting the value of copied cell

rng.Offset(0, 1).PasteSpecial xlPasteValues



'Unselecting the previous copied data and clearing the cache

Application.CutCopyMode = False



End If

Application.ScreenUpdating = True

Last:

Workbooks("Searching_And_Getting_Data_From_Other_File_Along_With_Formatting.xlsm").Activate



End Sub

如果您喜欢此博客,请在Facebook和Facebook上与您的朋友分享。

我们很希望收到您的来信,请让我们知道我们如何才能改善我们的工作并使您的工作更好。写信给我们[email protected]