이 기사에서는 정의 된 특정 조건에 따라 활성 통합 문서의 외부 통합 문서에서 데이터를 가져 오는 방법을 알아 봅니다.

이 예에서는 은행 카테고리의 이름과 유형을 기반으로 특정 개인에 대한 자금 세부 정보를 가져 오려고합니다. 자금 세부 정보는 “데이터 파일”통합 문서에 저장됩니다.

DataFile

이 예에서는 형식 스타일과 함께 돈 세부 정보를 반환하는 VBA 프로 시저 “ReadFormatting”을 작성했습니다.

논리 설명

“ReadFormatting”프로시 저는 범위 개체를 입력으로 사용하고 정의 된 범위 개체 옆의 셀에 출력을 반환합니다.

“데이터 파일”워크 북의 첫 번째 행 범위에서 정의 된 값을 확인하고 컬럼 번호를 찾습니다. “데이터 파일”워크 북의 첫 번째 열에서 정의 된 범위의 이전 열의 셀 값을 확인하고 행 번호를 찾습니다.

일치 가능한 열 번호와 행 번호를 찾은 후 찾은 열 번호와 행 번호가있는 셀의 값을 서식 스타일과 함께 반환합니다.

“ReadFormatting”절차는 다른 절차 또는 이벤트를 사용하여 실행할 수 있습니다.

두 가지 방법으로 “ReadFormatting”절차를 실행합니다. 절차 사용. 워크 시트 변경 이벤트 사용

절차 사용

N13 셀을 범위 객체로 사용하여 “ReadFormatting”프로 시저를 호출하기 위해 “CallingProcedure”프로 시저를 사용했습니다. 열 번호를 찾기 위해 외부 통합 문서의 첫 번째 행에있는 셀 N13의 값을 확인하고 행 번호를 찾기 위해 외부 통합 문서의 첫 번째 열에있는 셀 M13의 값을 확인합니다. 열 번호와 행 번호를 찾은 후 형식 스타일과 함께 값을 반환합니다.

ArrowRunningMacro

워크 시트 변경 이벤트 사용

워크 시트 변경 이벤트를 추가하려면 다음 단계를 따르십시오. 시트 모듈을 활성화하려면 Visual Basic Editor에서 시트 이름을 클릭합니다.

ArrowWritingWorksheetEvent

  1. 코드 창 상단의 왼쪽 콤보 상자에서 워크 시트를 클릭합니다.

ArrowWorksheetChangeEvent

  1. 코드 창 상단의 오른쪽 콤보 상자에서 변경 사항을 클릭합니다.

절차 실행을 위해 워크 시트 변경 이벤트를 사용했습니다. 통합 문서의 셀 값이 변경되면 워크 시트 변경 이벤트가 시작됩니다. IF 문을 사용하여 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]로 문의 해주세요