'SI개발/VBA'에 해당되는 글 6건

  1. 2023.02.03 [VBA] Format Yahoo Fantasy Players List
  2. 2022.12.11 [VBA]디렉토리 안의 파일 목록 구하기2
  3. 2021.03.27 [VBA] 차트 범례 추가, 삭제
  4. 2017.10.28 [VBA]디렉토리 안의 파일 목록 구하기
  5. 2016.03.27 [VBA] 엑셀 디아블로2 my log(엑셀), jimmy's log(본문)
  6. 2016.03.26 [VBA]Excel. DB칼럼명을 Camel, pascal로 변환

Since Yahoo doesn't provide the data in Excel or Txt format, I need to strip tags and remove blanks.

PlayerList(MLB)_v0.1_2023.xls
0.15MB
PlayerList(MLB)_v0.2_2023.xls
0.17MB

 

This is only the draft version and the VBA code will be updated.

 

Option Explicit

' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 0.1       2023-Feb-03             delRow(), findValue()
' 0.2       2023-Feb-03             getTeamName()
' **************************************************************************************

Sub delRow()
    'MsgBox ActiveCell.Range
    Dim lRowCnt, lCntAA, lCntAB As Long
    Dim rngAll As Range

    Application.ScreenUpdating = False
    Call stripTag 'remove tags
    
    lCntAA = Application.CountA(Range("A:A")) 'count of non blank cells under A
    lCntAB = Application.CountA(Range("B:B")) 'count of non blank cells under B
    
    If (lCntAA < lCntAB) Then '14 < 31
        'MsgBox "lCntAA < lCntAB"
        MsgBox "Columns are not destroyed."
        Columns("A").Delete
    Else '145 > 0
        'MsgBox "lCntAA >= lCntAB"
        MsgBox "Columns are split into rows."
    End If
    
    Cells(1, "A").Select
    Set rngAll = Range([A1], Cells(Rows.Count, "A").End(xlUp))
    lRowCnt = rngAll.Rows.Count
    Call findValue(lRowCnt) 'Delete the rows if the values are not needed
 
    'Cells(1, "B").Select
    'Set rngAll = Range([B1], Cells(Rows.Count, "B").End(xlUp))
    'lRowCnt = rngAll.Rows.Count
    'Call findValue(lRowCnt) 'Delete the rows if the values are not needed
    
    'Columns("A").SpecialCells(4).EntireRow.Delete 'delete empty cell rows
    'MsgBox Application.CountA(Range("A:A"))
    Range("A:A").RemoveDuplicates Columns:=1, Header:=xlYes 'delete ""
 
    Range("A1").Select
    ActiveWindow.ScrollRow = 1
    Application.ScreenUpdating = True
End Sub

Sub stripTag()
    'Cells.Select
    'Dim rngSelected As Range
    'Set rngSelected = New Cells.Select
    'Call stripHtml(rngSelected) 'remove html
    Cells.Hyperlinks.Delete     'remove hyperlink
    ActiveSheet.Pictures.Delete 'remove pictures
    
    'MsgBox Application.CountA(Range("A:A")) & ", " & Application.CountA(Range("B:B"))
    'MsgBox Len(Range("A9:A9"))
End Sub

Private Sub findValue(ByVal lRowCnt As Long)
    Dim i, r As Integer
    Dim sSheetName As String
    Dim sActiveCellValue As String
    
    sSheetName = getTeamName
    
    For i = 1 To lRowCnt
        sActiveCellValue = ActiveCell.Value
        If IsNumeric(sActiveCellValue) Then
            Selection.EntireRow.Delete
            lRowCnt = lRowCnt - 1
            r = r + 1
        ElseIf sActiveCellValue Like "*player Notes" Or sActiveCellValue Like "Player Note" Or sActiveCellValue = "DTD" Or sActiveCellValue = sSheetName Then
            Selection.EntireRow.Delete
            lRowCnt = lRowCnt - 1
            r = r + 1
        Else
            ActiveCell.Offset(1, 0).Select
        End If
    Next i
    MsgBox r & " rows deleted"

End Sub

Private Function getTeamName() As String
    On Error GoTo ec1
    Dim sSheetName As String
    Dim vSheetName As Variant
    
    sSheetName = ActiveSheet.Name
    vSheetName = Split(sSheetName, "(")
    'MsgBox vSheetName(0)
    
    getTeamName = vSheetName(0)
ec1:

End Function

파일이 자주 추가되거나 삭제될때 사용하기 위해 기존의 버전을 업그레이드 했습니다.

To Do List: 메인함수 module화

'Force the explicit declaration of variables
Option Explicit

' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2017-Oct-28             Initial Release
' 2         2017-Oct-28             Enter the folder name
' 3         2017-Oct-29             Use File Dialog
' 4         2022-Dec-11             Copy Sheet
' 5         2022-Dec-12             Add DateCreated
' 6         2022-Dec-26             addRow, setRowCnt
' 7         2022-Dec-28             Add one line of summary for statistics
' 8         2023-Jan-10             Format month and day(date)
' 9         2023-Jan-19             Total File Size, walkaround for the compile error of format(date, "mm")
' **************************************************************************************


Sub ListFiles()

     'Set a reference to Microsoft Scripting Runtime by using
     'Tools > References in the Visual Basic Editor (Alt+F11)
     
     'Declare the variables
     Dim objFSO As FileSystemObject
     Dim objFolder As Folder
     Dim objFile As File
     Dim strPath As String
     Dim strFile As String
     Dim NextRow As Long
     Dim dblFileSize As Double
     Dim dblFileTotalSize As Double
     
     
     'Added Codes Begin
     Dim Msg As String
     
     Call clearContents
     
     'Open the file dialog
     With Application.FileDialog(msoFileDialogFolderPicker)
        .AllowMultiSelect = False
        If .Show = -1 Then
            'MsgBox (.SelectedItems(1))
            strPath = .SelectedItems(1)
        Else
            Exit Sub
        End If
     End With
  
     
     'Msg = "Write down the folder name, please: " & vbCr
     'Msg = Msg & "e.g. C:\Users\Steve\Documents\Vids\"
     'strPath = Trim(InputBox(Msg, "Input"))
  
     If right(strPath, 1) <> "\" Then strPath = strPath & "\"
     
     'Added Codes End
     
     'Create an instance of the FileSystemObject
     Set objFSO = CreateObject("Scripting.FileSystemObject")
     
     'Get the folder
     Set objFolder = objFSO.GetFolder(strPath)
     
     'If the folder does not contain files, exit the sub
     If objFolder.Files.Count = 0 Then
         MsgBox "No files were found...", vbExclamation
         Exit Sub
     End If
     
     'Turn off screen updating
     Application.ScreenUpdating = False
     
     'Insert the headers for Columns A, B, C, and D
     Cells(1, "A").Value = "File Name"
     Cells(1, "B").Value = "Path"
     Cells(1, "C").Value = "Size"
     Cells(1, "D").Value = "Created Date"
     
     'Find the next available row
     NextRow = Cells(Rows.Count, "A").End(xlUp).Row + 1
     
     'Loop through each file in the folder
     For Each objFile In objFolder.Files
     
         'List the name, size, and date/time of the current file
         Cells(NextRow, 1).Value = objFile.Name
         'Cells(NextRow, 2).Value = objFile.Path
         Cells(NextRow, 2).Value = objFile.ParentFolder
         'Cells(NextRow, 3).Value = objFile.Size
         dblFileSize = objFile.Size
         Cells(NextRow, 3).Value = dblFileSize
         'Cells(NextRow, 3).Value = format(Round(dblFileSize / 1000000, 0), "#,#") & " MB" 'Format(n, "#,#")

         Cells(NextRow, 4).Value = objFile.DateCreated
         
         'Determine the next row
         NextRow = NextRow + 1
         dblFileTotalSize = dblFileTotalSize + dblFileSize
     
     Next objFile
     
     'Change the width of the columns to achieve the best fit
     'Columns.AutoFit
     'Format Cells
     Range(Cells(2, 3), Cells(Rows.Count, "D").End(xlUp)).Select
     Selection.HorizontalAlignment = xlRight
     Range(Cells(2, 4), Cells(Rows.Count, "D").End(xlUp)).Select
     Selection.NumberFormatLocal = "yyyy-mm-dd hh:mm"
     Selection.HorizontalAlignment = xlCenter
     Range("A1").Select
     
    Call copySheet
    
    Dim searchCnt As Long
    Dim Cell As Range
    For Each Cell In ActiveSheet.UsedRange.Columns(1).Cells
        If InStr(Cell.Value, "_error_") > 0 Then
            searchCnt = searchCnt + 1
        End If
    Next Cell
    'MsgBox "searchCnt = " & searchCnt
    
    Call addRow
    Call addFilter
    Call setRowCnt(searchCnt, dblFileTotalSize)
    Range("A1").Select
    
    'Turn screen updating back on
    Application.ScreenUpdating = True
         
End Sub

Private Sub clearContents()
    Worksheets("listFiles").Range("A1").EntireColumn.EntireRow.clearContents
End Sub

Private Sub copySheet()
    'Sheets(1).Copy after:=Sheets(1)
    Sheets(1).Copy after:=Sheets(ActiveWorkbook.Sheets.Count)
   
    'Remove Buttons
    Dim I As Long
    Dim xOLE As Object
    ActiveSheet.Buttons.Delete
    For Each xOLE In ActiveSheet.OLEObjects
        If TypeName(xOLE.Object) = "CommandButton" Then
            xOLE.Delete
        End If
    Next
  
    Dim n As Integer
    Dim shtName As String
    Dim dtToday As Date
    Dim sMonth As String
    
    'MsgBox (Year(Date) & Month(Date) & Day(Date))
    'shtName = "List_" & Year(Date) & Month(Date) & Day(Date)
    dtToday = Date
    sMonth = Month(dtToday)
    If Len(sMonth) = 1 Then
        sMonth = "0" & sMonth
    End If
    'shtName = "List_" & Year(dtToday) & format(dtToday, "mm") & format(dtToday, "dd")
    shtName = "List_" & Year(dtToday) & sMonth & format(dtToday, "dd")
    
    
    'Format(Now, "yyyy/mm/dd/hh/mm/ss")
    'dtToday = Now
    'shtName = "List_" & Year(Now) & Month(Now) & Day(Now) & Hour(Now) & Minute(Now) & Second(Now)
    'shtName = "List_" & Year(dtToday) & Month(dtToday) & Day(dtToday) & Hour(dtToday) & Minute(dtToday) & Second(dtToday)
    'shtName = "List_" & Year(dtToday) & format(dtToday, "mm") & Day(dtToday) & Hour(dtToday) & Minute(dtToday) & Second(dtToday)
    
    
    Do While (shCheck(shtName))
        shtName = shtName & " (2)"
        'shtName = Replace(shtName, "_", "")
    Loop
    'Sheets(2).Name = shtName
    ActiveSheet.Name = shtName
End Sub

' 해당시트가 있으면 True를, 그렇지 않으면 False 를 반환합니다
Private Function shCheck(shName$) As Boolean
   On Error GoTo ec1
   If CBool(Len(Sheets(shName$).Name)) Then shCheck = True
   Exit Function
ec1:
   shCheck = False
End Function

Private Sub addRow()
    Rows("1:1").Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub

Private Sub addFilter()
    Range("A2:D2").Select
    Selection.AutoFilter
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    Selection.Font.Bold = True
    Range("B3").Select
    ActiveWindow.FreezePanes = True
    
    'Range("A1").Select
End Sub

Private Sub setRowCnt(ByVal searchCnt As Long, ByVal dblFileTotalSize As Double)
    'MsgBox "searchCnt = " & searchCnt
    Dim rowCnt As Long
    rowCnt = Range("a3", Range("a2").End(xlDown)).Rows.Count
    rowCnt = rowCnt - searchCnt
    
    Cells(1, 1) = "Number of Working Games"
    Cells(1, 2) = rowCnt
    Cells(1, 3) = "Excluded"
    Cells(1, 4) = searchCnt
    Cells(1, 5) = "Total Size"

    If (dblFileTotalSize > 1000000000) Then
        Cells(1, 6) = format(Round(dblFileTotalSize / 1000000000, 0), "#,#") & " GB" 'Format(n, "#,#")
    Else
        Cells(1, 6) = dblFileTotalSize
    End If
    
    Range("A1").Select
    Selection.HorizontalAlignment = xlCenter
    Range("C1").Select
    Selection.HorizontalAlignment = xlCenter
    Columns("E:E").EntireColumn.AutoFit
    Range("E1").Select
    Selection.HorizontalAlignment = xlCenter
    Columns("F:F").EntireColumn.AutoFit
    Range("F1").Select
    Selection.Style = "Comma [0]"
    
End Sub

listFiles_v4_20221211.xls
0.40MB
listFiles_v5_20221212_upload.xls
0.25MB
listFiles_v6_20221226.xls
0.16MB

※ 서브 디렉토리 포함(기존에 됐었던 것 같은데, 안되네요. 필요시 다음 링크 참조)

[vba] 하위폴더 내의 모든 파일 정보 가져오기 :: 개발하는 디자이너의 DIY 일상 (tistory.com)

 

[vba] 하위폴더 내의 모든 파일 정보 가져오기

일을 하다 보면 가끔 업무를 진행하던 경로 하위에 있는 데이들의 리스트를 만들어야 하는 경우가 있습니다. 하나의 폴더라면 어떻게 해보겠는데 그 폴더가 하위 뎁스가 연속해서 있고 저장되

diy-dev-design.tistory.com

 

부동산 실거래가 자료를 기록하기 시작했습니다. 버전이 2007이다 보니 동적 레전드 기능이 안되서 vba로 작성했습니다. 생각나는대로 기능위주로 만들다보니 Module화랑 Interface가 빈약한 점은 추후 개선해보도록 하겠습니다. 파일은 주요 아파트가 기록이 되어있기에 삭제되는대로 첨부하겠습니다.

 

' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2021-03-25             Initial Release
' **************************************************************************
'Force the explicit declaration of variables
Option Explicit
Sub add_Click()
    Call add    '계열 추가 호출
End Sub
Sub del_Click()
    Call del '계열 삭제 호출
End Sub
Sub copy_Click()
    Call copyRange  '범위 복사 호출
End Sub
Sub copyNm_Click()
    Call copyNm     '이름 복사 호출
End Sub
Sub init_Click()
    Call initialize '초기화 호출
End Sub
Sub sort_Click()
    Call sortRoi    '수익률 정렬
End Sub


'계열 추가
Private Sub add()
    'ActiveChart.PlotArea.Select
    If ActiveChart Is Nothing Then
        MsgBox "차트를 선택해주세요", vbExclamation, "Chart"
        Exit Sub
    Else
    End If
    
    Dim lngSerCnt, lngLastRow As Long
    Dim strDel As String
    Dim strAddSrs As String
    lngSerCnt = ActiveChart.SeriesCollection.Count + 1
    
    strDel = Trim(ActiveSheet.OLEObjects("txtDel").Object.Text)
    'strDel = Replace(strDel, Chr(10), "") 'vbLf
    'strDel = Replace(strDel, Chr(13), "") 'vbCr
    If strDel = "" Then
        MsgBox "추가할 계열명을 입력해주세요", vbExclamation, "Chart"
        Exit Sub
    End If
    
    strAddSrs = Trim(ActiveSheet.OLEObjects("txtAddSrs").Object.Text)
    If strAddSrs = "" Then
        MsgBox "계열범위를 복사해주세요", vbExclamation, "Chart"
        Exit Sub
    End If
    
    'lngLastRow = Cells(1, 1).End(xlDown).Row
    'MsgBox lngLastRow
    
    Application.ScreenUpdating = False
    ActiveChart.SeriesCollection.NewSeries
    'ActiveChart.SeriesCollection(lngSerCnt).Name = "=서울!$D$2"
    ActiveChart.SeriesCollection(lngSerCnt).Name = strDel
    'ActiveChart.SeriesCollection(lngSerCnt).Values = "=서울!$D$3:$D$22"
    ActiveChart.SeriesCollection(lngSerCnt).Values = "=서울!" & strAddSrs & ""
    'Call initialize '초기화 호출
    Application.ScreenUpdating = True
End Sub

'계열 삭제
Private Sub del()
    'Declare the variables
    Dim lngSerCnt As Long
    Dim strDel As String
        
    'ActiveChart.PlotArea.Select
    If ActiveChart Is Nothing Then
        MsgBox "차트를 선택해주세요", vbExclamation, "Chart"
        
        Exit Sub
    Else
    End If

    'MsgBox ActiveSheet.OLEObjects("txtDel").Object.Value, vbExclamation, "Chart"
    strDel = Trim(ActiveSheet.OLEObjects("txtDel").Object.Text)
    strDel = Replace(strDel, Chr(10), "") 'vbLf
    strDel = Replace(strDel, Chr(13), "") 'vbCr
    strDel = Trim(strDel)
    'MsgBox strDel, vbExclamation, "Chart"

    If strDel = "" Then
        MsgBox "삭제할 계열명을 입력해주세요", vbExclamation, "Chart"
        Exit Sub
    End If

    Application.ScreenUpdating = False
    
    With ActiveChart
     DoEvents
        For lngSerCnt = .SeriesCollection.Count To 1 Step -1
            If .SeriesCollection(lngSerCnt).Name = strDel Then .SeriesCollection(lngSerCnt).Delete
        Next lngSerCnt
    End With
    Call initialize '초기화 호출
    Application.ScreenUpdating = True
End Sub

'초기화
Private Sub initialize()
    ActiveSheet.OLEObjects("txtDel").Object.Text = ""
    ActiveSheet.OLEObjects("txtAddSrs").Object.Text = ""
End Sub

'이름 복사
Private Sub copyNm()
    Dim strSelRng As String 'Selection.Address
    
    If ActiveChart Is Nothing Then
        strSelRng = Selection.Text
        If strSelRng = "" Then
            MsgBox "선택하신 계열명이 공백입니다.", vbExclamation, "Chart"
            ActiveSheet.OLEObjects("txtDel").Object.Text = ""
            Exit Sub
        End If
        ActiveSheet.OLEObjects("txtDel").Object.Text = strSelRng
    Else
        
        MsgBox "계열명을 선택해주세요", vbExclamation, "Chart"
        ActiveSheet.OLEObjects("txtDel").Object.Text = ""
        Exit Sub
    End If

End Sub

'범위 복사
Private Sub copyRange()
    'Range("서울").CurrentRegion.Copy
    Dim strSelRng As String 'Selection.Address
    
    If ActiveChart Is Nothing Then
        strSelRng = Selection.Address
        ActiveSheet.OLEObjects("txtAddSrs").Object.Text = strSelRng
    Else
        MsgBox "복사할 범위를 선택해주세요", vbExclamation, "Chart"
        ActiveSheet.OLEObjects("txtAddSrs").Object.Text = ""
        Exit Sub
    End If
End Sub

'수익률 정렬
Private Sub sortRoi()
    Dim strSelCell As String '선택셀
    Dim LastRow As Long
    Dim rngSort As Range '정렬범위
    strSelCell = ActiveCell.Address
   
    Worksheets("ROI").Range("A1").EntireColumn.EntireRow.Clear 'Sheet(ROI) 초기화
    
    'Copy
    Worksheets("서울").Range("A2").EntireRow.Select
    Selection.Copy
    Sheets("ROI").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
    
    Worksheets("서울").Activate
    Worksheets("서울").Range(strSelCell).EntireRow.Select
    Selection.Copy
    Sheets("ROI").Select
    Range("B1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True

    'Delete empty rows
    Columns("B").SpecialCells(4).EntireRow.Delete
    Columns("A:A").EntireColumn.AutoFit
    
    Range(Range("A1", "B1"), Range("A1:B1").End(xlDown)).Select
    Set rngSort = Selection
    
    ActiveWorkbook.Worksheets("ROI").Sort.SortFields.Clear
    'ActiveWorkbook.Worksheets("ROI").Sort.SortFields.add Key:=Range("B2:B11"),
    ActiveWorkbook.Worksheets("ROI").Sort.SortFields.add Key:=Range("B2", Range("B2").End(xlDown)), _
        SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("ROI").Sort
        '.SetRange Range("A1:B11")
        .SetRange rngSort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    
    'cell형식: 비율
    Range("B2", Range("B2").End(xlDown)).Select
    Selection.Style = "Percent"
    
    '테두리
    rngSort.Select
    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
    With Selection.Borders(xlEdgeLeft)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeRight)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlInsideVertical)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlInsideHorizontal)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    
    '제목 가운데 정렬
    Range("A1:B1").Select
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    
    Range("A1").Select

End Sub

디렉토리(폴더)내의 파일 목록을 구하는 함수입니다.

다중선택은 안되고, 서브폴더까지 검색합니다.

ToDo: Target root 폴더에 파일이 없으면 종료되는 문제(서브디렉토리 파일 count까지 합하도록 변경 필요) -> 이부분 해결 방법 아시는 분은 댓글 남겨주시면 감사하겠습니다.

 

listFiles_v3.xls

 

내용은 다음과 같습니다.

'Force the explicit declaration of variables
Option Explicit

' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2017-Oct-28             Initial Release
' 2         2017-Oct-28             Enter the folder name
' 3         2017-Oct-29             Use File Dialog
' **************************************************************************************


Sub ListFiles()
     'Declare the variables
     Dim objFSO As FileSystemObject
     Dim objFolder As Folder
     Dim objFile As File
     Dim strPath As String
     Dim strFile As String
     Dim NextRow As Long
    
     'Added Codes Begin
     Dim Msg As String
    
     Call clearContents
    
     'Open the file dialog
     With Application.FileDialog(msoFileDialogFolderPicker)
        .AllowMultiSelect = False
        If .Show = -1 Then
            'MsgBox (.SelectedItems(1))
            strPath = .SelectedItems(1)
        Else
            Exit Sub
        End If
     End With
 
    
     'Msg = "Write down the folder name, please: " & vbCr
     'Msg = Msg & "e.g. C:\Users\Steve\Documents\Vids\"
     'strPath = Trim(InputBox(Msg, "Input"))
 
     If right(strPath, 1) <> "\" Then strPath = strPath & "\"
    
     'Added Codes End
    
     'Create an instance of the FileSystemObject
     Set objFSO = CreateObject("Scripting.FileSystemObject")
    
     'Get the folder
     Set objFolder = objFSO.GetFolder(strPath)
    
     'If the folder does not contain files, exit the sub
     If objFolder.Files.Count = 0 Then
         MsgBox "No files were found...", vbExclamation
         Exit Sub
     End If
    
     'Turn off screen updating
     Application.ScreenUpdating = False
    
     'Insert the headers for Columns A, B, and C
     Cells(1, "A").Value = "FileName"
     Cells(1, "B").Value = "Path"
     Cells(1, "C").Value = "Size"
    
     'Find the next available row
     NextRow = Cells(Rows.Count, "A").End(xlUp).Row + 1
    
     'Loop through each file in the folder
     For Each objFile In objFolder.Files
    
         'List the name, size, and date/time of the current file
         Cells(NextRow, 1).Value = objFile.Name
         Cells(NextRow, 2).Value = objFile.Path
         Cells(NextRow, 3).Value = objFile.Size
        
         'Determine the next row
         NextRow = NextRow + 1
    
     Next objFile
    
     'Change the width of the columns to achieve the best fit
     'Columns.AutoFit
    
     'Turn screen updating back on
     Application.ScreenUpdating = True
        
End Sub

Sub clearContents()
    Worksheets("List").Range("A1").EntireColumn.EntireRow.clearContents
End Sub

 

 

ItemListv0.7_20160327.xls

 

 

 

 

Sub DeleteEmptyRows()
    LastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count
    Application.ScreenUpdating = False
    For r = LastRow To 1 Step -1
        If Application.CountA(Rows(r)) = 0 Then Rows(r).Delete
    Next r
End Sub

Sub DeleteEmptyHeaders()
    'Delete the row if column A is empty
    LastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count
    Application.ScreenUpdating = False
    For r = LastRow To 2 Step -1 'Exclude the first row from the range
        'If Application.CountA(Rows(r)) = 0 Then Rows(r).Delete
        If Application.CountA(Cells(r, 1)) = 0 Then Rows(r).Delete
    Next r
    removeColor
End Sub

Sub sortJefOS()
'
' sortJefOS Macro
'
' Hardcoded for only one worksheet of Jimmy's log(Jef-X: Magic&OS)

    Dim srt As Sort
       
    Set srt = ActiveSheet.Sort
   
    With srt.SortFields
        .Clear
        .Add Key:=Columns("H"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal 'Number of sockets
        .Add Key:=Columns("I"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal 'Base
        .Add Key:=Columns("A"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal 'Account
        .Add Key:=Columns("B"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal 'Character
    End With
   
    'With ActiveWorkbook.Worksheets("Magic&OS").Sort
    With srt
        .SetRange Cells
        .Header = xlYes             'My data has headers
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
   
    DeleteEmptyHeaders
End Sub

Sub removeColor()
    Cells.Select
    With Selection.Interior
        .Pattern = xlNone
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
End Sub
Sub stripTag()
    'Cells.Select
    'Dim rngSelected As Range
    'Set rngSelected = New Cells.Select
    'Call stripHtml(rngSelected) 'html제거
    Cells.Hyperlinks.Delete 'hyperlink 제거
    ActiveSheet.Pictures.Delete '그림 제거
End Sub
Function stripHtml(cell As Range) As String

Dim RegEx As Object
 Set RegEx = CreateObject("vbscript.regexp")
Dim sInput As String
 Dim sOut As String
 sInput = cell.Text

sInput = Replace(sInput, "\x0D\x0A", Chr(10))
 sInput = Replace(sInput, "\x00", Chr(10))

'replace HTML breaks and end of paragraphs with line breaks
 sInput = Replace(sInput, "</P>", Chr(10) & Chr(10))
 sInput = Replace(sInput, "<BR>", Chr(10))

'replace bullets with dashes
 sInput = Replace(sInput, "<li>", "-")

'add back all of the special characters
 sInput = Replace(sInput, "&ndash;", "?")
sInput = Replace(sInput, "&mdash;", "?")
sInput = Replace(sInput, "&iexcl;", "¡")
sInput = Replace(sInput, "&iquest;", "¿")
sInput = Replace(sInput, "&quot;", "")
sInput = Replace(sInput, "&ldquo;", "“")
sInput = Replace(sInput, "&rdquo;", "”")
sInput = Replace(sInput, "", "‘")
sInput = Replace(sInput, "&lsquo;", "‘")
sInput = Replace(sInput, "&rsquo;", "’")
sInput = Replace(sInput, "&laquo;", "≪")
sInput = Replace(sInput, "&raquo;", "≫")
sInput = Replace(sInput, "&nbsp;", " ")
sInput = Replace(sInput, "&amp;", "&")
sInput = Replace(sInput, "&cent;", "¢")
sInput = Replace(sInput, "&copy;", "ⓒ")
sInput = Replace(sInput, "&divide;", "÷")
sInput = Replace(sInput, "&gt;", ">")
sInput = Replace(sInput, "&lt;", "<")
sInput = Replace(sInput, "&micro;", "μ")
sInput = Replace(sInput, "&middot;", "·")
sInput = Replace(sInput, "&para;", "¶")
sInput = Replace(sInput, "&plusmn;", "±")
sInput = Replace(sInput, "&euro;", "€")
sInput = Replace(sInput, "&pound;", "£")
sInput = Replace(sInput, "&reg;", "®")
sInput = Replace(sInput, "&sect;", "§")
sInput = Replace(sInput, "&trade;", "™")
sInput = Replace(sInput, "&yen;", "¥")
sInput = Replace(sInput, "&aacute;", "a")
sInput = Replace(sInput, "&Aacute;", "A")
sInput = Replace(sInput, "&agrave;", "a")
sInput = Replace(sInput, "&Agrave;", "A")
sInput = Replace(sInput, "&acirc;", "a")
sInput = Replace(sInput, "&Acirc;", "A")
sInput = Replace(sInput, "&aring;", "a")
sInput = Replace(sInput, "&Aring;", "A")
sInput = Replace(sInput, "&atilde;", "a")
sInput = Replace(sInput, "&Atilde;", "A")
sInput = Replace(sInput, "&auml;", "a")
sInput = Replace(sInput, "&Auml;", "A")
sInput = Replace(sInput, "&aelig;", "æ")
sInput = Replace(sInput, "&AElig;", "Æ")
sInput = Replace(sInput, "&ccedil;", "c")
sInput = Replace(sInput, "&Ccedil;", "C")
sInput = Replace(sInput, "&eacute;", "e")
sInput = Replace(sInput, "&Eacute;", "E")
sInput = Replace(sInput, "&egrave;", "e")
sInput = Replace(sInput, "&Egrave;", "E")
sInput = Replace(sInput, "&ecirc;", "e")
sInput = Replace(sInput, "&Ecirc;", "E")
sInput = Replace(sInput, "&euml;", "e")
sInput = Replace(sInput, "&Euml;", "E")
sInput = Replace(sInput, "&iacute;", "i")
sInput = Replace(sInput, "&Iacute;", "I")
sInput = Replace(sInput, "&igrave;", "i")
sInput = Replace(sInput, "&Igrave;", "I")
sInput = Replace(sInput, "&icirc;", "i")
sInput = Replace(sInput, "&Icirc;", "I")
sInput = Replace(sInput, "&iuml;", "i")
sInput = Replace(sInput, "&Iuml;", "I")
sInput = Replace(sInput, "&ntilde;", "n")
sInput = Replace(sInput, "&Ntilde;", "N")
sInput = Replace(sInput, "&oacute;", "o")
sInput = Replace(sInput, "&Oacute;", "O")
sInput = Replace(sInput, "&ograve;", "o")
sInput = Replace(sInput, "&Ograve;", "O")
sInput = Replace(sInput, "&ocirc;", "o")
sInput = Replace(sInput, "&Ocirc;", "O")
sInput = Replace(sInput, "&oslash;", "ø")
sInput = Replace(sInput, "&Oslash;", "Ø")
sInput = Replace(sInput, "&otilde;", "o")
sInput = Replace(sInput, "&Otilde;", "O")
sInput = Replace(sInput, "&ouml;", "o")
sInput = Replace(sInput, "&Ouml;", "O")
sInput = Replace(sInput, "&szlig;", "ß")
sInput = Replace(sInput, "&uacute;", "u")
sInput = Replace(sInput, "&Uacute;", "U")
sInput = Replace(sInput, "&ugrave;", "u")
sInput = Replace(sInput, "&Ugrave;", "U")
sInput = Replace(sInput, "&ucirc;", "u")
sInput = Replace(sInput, "&Ucirc;", "U")
sInput = Replace(sInput, "&uuml;", "u")
sInput = Replace(sInput, "&Uuml;", "U")
sInput = Replace(sInput, "&yuml;", "y")
sInput = Replace(sInput, "", "´")
sInput = Replace(sInput, "", "`")

'replace all the remaining HTML Tags
 With RegEx
 .Global = True
 .IgnoreCase = True
 .MultiLine = True
 .Pattern = "<[^>]+>" 'Regular Expression for HTML Tags.

End With
 sOut = RegEx.Replace(sInput, "")
stripHtml = sOut
 Set RegEx = Nothing

End Function

 

현재 프로젝트의 단순작업에 걸리는 시간을 줄이기 위해 만들어봤습니다.

단순한 코딩이고요. 개선하실 사안이 있으시면 변경하시거나 의견주셔도 됩니다.

파일 첨부했어요.

 

fab.xls - 초기버전

 

fab_v2.xls - LastRow를 변수로 교체

 

 

즐코딩~

 

코드만 보시려는 분들을 위해 내용도 붙여넣을께요

 

'---------------------------------------------------------------------------------------
' Procedure : Convert DB column names to Camel and Pascal cases
' Author    : Sean
' Purpose   : Reduce repetitive and time consuming converting tasks
' Copyright : I do not claim any copyrights over this code. The following may be altered and reused as you wish
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' DB Column Names   : Place column names in column A of Columns sheet.
'
' Usage:
' ~~~~~~
' ?camelCase()
'       Convert to Camel Case
' ?pascalCase()
'       Convert to Pascal Case
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2016-Mar-26             Initial Release
' **************************************************************************************
' Columns: DB column names
' Components: Nexacro component names
' Variables: VO variable and dataset column names
'
' ToDo.1: For문의 max값은 Range(Selection, Selection.End(xlDown)).Select 등을 이용하여 상수에서 변수로 변경.
'

Sub convert()
    'MsgBox "test"
  
    Worksheets("Components").Range("A1").EntireColumn.EntireRow.clearContents
    Worksheets("Variables").Range("A1").EntireColumn.EntireRow.clearContents
   
    copyRows
    Application.CutCopyMode = False
   
   
    Worksheets("Columns").Select
    Range("A1").Select
   
    pascalCase  'Components
    camelCase   'Variables

End Sub

Sub copyRows()
    Worksheets("Columns").Range("A1").EntireColumn.Select
    Selection.Copy
   
    Sheets("Variables").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
       
    Sheets("Components").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
End Sub

Sub pascalCase()
    Dim strCase As String
   
    Worksheets("Components").Select
    For x = 1 To 65536
        If (Len(Cells(x, 1)) > 0) Then
            strCase = Application.Substitute(Application.Proper(Cells(x, 1)), "_", "")
            strCase = "_" & strCase
            Cells(x, 1) = strCase
        End If
    Next
   
End Sub

Sub camelCase()
    Dim strCase As String
   
    Worksheets("Variables").Select
    'For Each x In Range("A1").EntireColumn
    For x = 1 To 65536
        'x.Value = LCase(x.Value)
        If (Len(Cells(x, 1)) > 0) Then
            strCase = Application.Substitute(Application.Proper(Cells(x, 1)), "_", "")
       
            'If (Len(strCase) > 0) Then
                Mid(strCase, 1, 1) = LCase(Mid(strCase, 1, 1))
            'End If
            Cells(x, 1) = strCase
        End If
    Next
   
End Sub

Sub clearContents()
    Worksheets("Columns").Range("A1").EntireColumn.EntireRow.clearContents
    Worksheets("Components").Range("A1").EntireColumn.EntireRow.clearContents
    Worksheets("Variables").Range("A1").EntireColumn.EntireRow.clearContents
End Sub

1 

글 보관함

카운터

Total : / Today : / Yesterday :
get rsstistory!