해결 M365윈도우11
여러 파일에서 코드 반복 수행 시 중첩 문제
안녕하세요,
폴더안의 여러 파일 돌면서 같은 코드 반복시키는 코드를 만들었는데, 수행해서 값을 구하고 다음 파일 돌면서 같은 자리에 계속 덮어쓰기가 되는거 같습니다 .
그런데 또 다음파일은 그 밑으로 입력이 되기도 하구요.
챗지피티 돌려봐도 도무지 고쳐지지가 않네요.
고수분들, 코드 좀 확인 부탁드리겠습니다
Sub CallingRecentMOs()
Dim folderPath As String
Dim fileName As String
Dim wb As Workbook
Dim ws As Worksheet
Dim ws3 As Worksheet ' 시트3 추가
Dim lastColumn15 As Long
Dim i As Long, j As Long
Dim targetDate As Date
Dim foundColumn As Long
Dim outputRow3 As Long ' 시트3 출력 행 변수 추가
Dim foundNewDate As Boolean
Dim multiplier As Double ' C6 셀 값 저장 변수
' 현재 엑셀 파일이 있는 폴더 경로 가져오기
folderPath = ThisWorkbook.Path & "\"
' 폴더 내의 모든 엑셀 파일 순회
fileName = Dir(folderPath & "*.xlsx")
' 초기 Dir 호출 후 첫 번째 파일이 없으면 루프를 실행하지 않도록 수정
If Len(fileName) = 0 Then
MsgBox "해당 폴더에 엑셀 파일이 없습니다.", vbExclamation
Exit Sub
End If
' 현재 엑셀 파일의 이름 변수에 저장
Dim currentWorkbookName As String
currentWorkbookName = ThisWorkbook.Name
Do While Len(fileName) > 0
' 현재 엑셀 파일은 제외
If fileName <> currentWorkbookName Then
On Error Resume Next ' 파일 열기 오류 발생 시 다음 파일로
' 엑셀 파일 열기
Set wb = Workbooks.Open(folderPath & fileName)
Set ws = wb.Sheets(1) ' 열려 있는 파일의 시트1
Set ws3 = ThisWorkbook.Sheets(3) ' 현재 워크북의 시트3 설정
If Err.Number <> 0 Then
MsgBox fileName & " 파일을 열 수 없습니다.", vbExclamation
Err.Clear
GoTo NextFile
End If
' B1 셀의 날짜 가져오기
If IsDate(ws3.Range("B1").Value) Then
targetDate = ws3.Range("B1").Value
Else
MsgBox "B1 셀에 유효한 날짜가 없습니다."
wb.Close SaveChanges:=False
GoTo NextFile
End If
' C6 셀의 값 가져오기
If IsNumeric(ws.Range("C6").Value) Then
multiplier = ws.Range("C6").Value
Else
MsgBox "C6 셀에 숫자가 없습니다."
wb.Close SaveChanges:=False
GoTo NextFile
End If
' 시트3 A3부터 출력할 행 초기화
outputRow3 = 3
Do
' 15행의 마지막 사용 열 찾기
lastColumn15 = ws.Cells(15, ws.Columns.Count).End(xlToLeft).Column
' 찾은 열 초기화
foundColumn = 0
foundNewDate = False
' 15행에서 AX2 날짜보다 큰 첫 번째 셀 찾기
For i = 6 To lastColumn15
If IsDate(ws.Cells(15, i).Value) Then
If ws.Cells(15, i).Value > targetDate Then
foundColumn = i
foundNewDate = True
targetDate = ws.Cells(15, i).Value ' 다음 검색을 위해 targetDate 업데이트
Exit For ' 첫 번째 찾은 셀에서 루프 종료
End If
End If
Next i
' 찾은 열이 없으면 루프 종료
If foundColumn = 0 Then
Exit Do
End If
' 찾은 열의 27행 이하 데이터 찾아서 시트3 A3부터 나열
For j = 27 To ws.Rows.Count
If ws.Cells(j, foundColumn).Value <> "" Then
ws3.Cells(outputRow3, "A").Value = ws.Cells(7, foundColumn).Value
outputRow3 = outputRow3
ws3.Cells(outputRow3, "B").Value = ws.Cells(8, foundColumn).Value
outputRow3 = outputRow3
ws3.Cells(outputRow3, "C").Value = ws.Cells(j, 4).Value
outputRow3 = outputRow3
ws3.Cells(outputRow3, "K").Value = ws.Cells(j, foundColumn).Value * multiplier ' C6 곱하기
outputRow3 = outputRow3 + 1 ' 시트3 출력 행 증가
End If
Next j
Loop While foundNewDate
' 엑셀 파일 닫기
wb.Close SaveChanges:=False
NextFile:
' 다음 파일로
fileName = Dir
Set wb = Nothing
Set ws = Nothing
Else
' 현재 엑셀 파일은 건너뜀
fileName = Dir
End If
Loop
MsgBox "모든 엑셀 파일 처리가 완료되었습니다.", vbInformation
' 정리
Set ws3 = Nothing ' 시트3 개체 해제
End Sub
폴더안의 여러 파일 돌면서 같은 코드 반복시키는 코드를 만들었는데, 수행해서 값을 구하고 다음 파일 돌면서 같은 자리에 계속 덮어쓰기가 되는거 같습니다 .
그런데 또 다음파일은 그 밑으로 입력이 되기도 하구요.
챗지피티 돌려봐도 도무지 고쳐지지가 않네요.
고수분들, 코드 좀 확인 부탁드리겠습니다
Sub CallingRecentMOs()
Dim folderPath As String
Dim fileName As String
Dim wb As Workbook
Dim ws As Worksheet
Dim ws3 As Worksheet ' 시트3 추가
Dim lastColumn15 As Long
Dim i As Long, j As Long
Dim targetDate As Date
Dim foundColumn As Long
Dim outputRow3 As Long ' 시트3 출력 행 변수 추가
Dim foundNewDate As Boolean
Dim multiplier As Double ' C6 셀 값 저장 변수
' 현재 엑셀 파일이 있는 폴더 경로 가져오기
folderPath = ThisWorkbook.Path & "\"
' 폴더 내의 모든 엑셀 파일 순회
fileName = Dir(folderPath & "*.xlsx")
' 초기 Dir 호출 후 첫 번째 파일이 없으면 루프를 실행하지 않도록 수정
If Len(fileName) = 0 Then
MsgBox "해당 폴더에 엑셀 파일이 없습니다.", vbExclamation
Exit Sub
End If
' 현재 엑셀 파일의 이름 변수에 저장
Dim currentWorkbookName As String
currentWorkbookName = ThisWorkbook.Name
Do While Len(fileName) > 0
' 현재 엑셀 파일은 제외
If fileName <> currentWorkbookName Then
On Error Resume Next ' 파일 열기 오류 발생 시 다음 파일로
' 엑셀 파일 열기
Set wb = Workbooks.Open(folderPath & fileName)
Set ws = wb.Sheets(1) ' 열려 있는 파일의 시트1
Set ws3 = ThisWorkbook.Sheets(3) ' 현재 워크북의 시트3 설정
If Err.Number <> 0 Then
MsgBox fileName & " 파일을 열 수 없습니다.", vbExclamation
Err.Clear
GoTo NextFile
End If
' B1 셀의 날짜 가져오기
If IsDate(ws3.Range("B1").Value) Then
targetDate = ws3.Range("B1").Value
Else
MsgBox "B1 셀에 유효한 날짜가 없습니다."
wb.Close SaveChanges:=False
GoTo NextFile
End If
' C6 셀의 값 가져오기
If IsNumeric(ws.Range("C6").Value) Then
multiplier = ws.Range("C6").Value
Else
MsgBox "C6 셀에 숫자가 없습니다."
wb.Close SaveChanges:=False
GoTo NextFile
End If
' 시트3 A3부터 출력할 행 초기화
outputRow3 = 3
Do
' 15행의 마지막 사용 열 찾기
lastColumn15 = ws.Cells(15, ws.Columns.Count).End(xlToLeft).Column
' 찾은 열 초기화
foundColumn = 0
foundNewDate = False
' 15행에서 AX2 날짜보다 큰 첫 번째 셀 찾기
For i = 6 To lastColumn15
If IsDate(ws.Cells(15, i).Value) Then
If ws.Cells(15, i).Value > targetDate Then
foundColumn = i
foundNewDate = True
targetDate = ws.Cells(15, i).Value ' 다음 검색을 위해 targetDate 업데이트
Exit For ' 첫 번째 찾은 셀에서 루프 종료
End If
End If
Next i
' 찾은 열이 없으면 루프 종료
If foundColumn = 0 Then
Exit Do
End If
' 찾은 열의 27행 이하 데이터 찾아서 시트3 A3부터 나열
For j = 27 To ws.Rows.Count
If ws.Cells(j, foundColumn).Value <> "" Then
ws3.Cells(outputRow3, "A").Value = ws.Cells(7, foundColumn).Value
outputRow3 = outputRow3
ws3.Cells(outputRow3, "B").Value = ws.Cells(8, foundColumn).Value
outputRow3 = outputRow3
ws3.Cells(outputRow3, "C").Value = ws.Cells(j, 4).Value
outputRow3 = outputRow3
ws3.Cells(outputRow3, "K").Value = ws.Cells(j, foundColumn).Value * multiplier ' C6 곱하기
outputRow3 = outputRow3 + 1 ' 시트3 출력 행 증가
End If
Next j
Loop While foundNewDate
' 엑셀 파일 닫기
wb.Close SaveChanges:=False
NextFile:
' 다음 파일로
fileName = Dir
Set wb = Nothing
Set ws = Nothing
Else
' 현재 엑셀 파일은 건너뜀
fileName = Dir
End If
Loop
MsgBox "모든 엑셀 파일 처리가 완료되었습니다.", vbInformation
' 정리
Set ws3 = Nothing ' 시트3 개체 해제
End Sub
마
사
진
댓글 5
Do Loop 사이 부분을 검토해보시고..
lastColumn15 = ws.Cells(15, ws.Columns.Count).End(xlToLeft).Column
이 코드 이전에 Stop을 넣어서 lastcolumn이 찾아지는지 확인해보십시오.
이 코드가 첫번째 Do 루프의 위로 올라가야 하지 않을까 싶네요.
첫번째 Do 루프 안에 있어서 항상 같은 행부터 시작해서 덮어쓰기 하는 것 같습니다.
가끔 새 줄에 써지는 이유는 발견된 새 날짜가 기존 파일보다 많은 경우에 초과되는 날짜가 아래로 기재되지 싶습니다.