2014-02-19 7 views
2

선택한 폴더에있는 각 파일의 행 수를 계산 한 다음 활성 통합 문서에 표시하려면 VBA 스크립트를 실행하고 있습니다.VBA에서 셀의 파일 경로를 사용하는 방법?

Option Explicit 
Sub CountRows() 
    Dim wbSource As Workbook, wbDest As Workbook 
    Dim wsSource As Worksheet, wsDest As Worksheet 
    Dim strFolder As String, strFile As String 
    Dim lngNextRow As Long, lngRowCount As Long 

    Application.ScreenUpdating = False 

    Set wbDest = ActiveWorkbook 
    Set wsDest = wbDest.ActiveSheet 

    strFolder = Dir(Range("C7").Value) 
    strFile = Dir(strFolder & "*.xlsx") 
    lngNextRow = 11 
    Do While Len(strFile) > 0 
     Set wbSource = Workbooks.Open(Filename:=strFolder & strFile) 
     Set wsSource = wbSource.Worksheets(1) 
     lngRowCount = wsSource.UsedRange.Rows.Count 
     wsDest.Cells(lngNextRow, "F").Value = lngRowCount 
     wbSource.Close savechanges:=False 
     lngNextRow = lngNextRow + 1 
     strFile = Dir 
    Loop 

    Application.ScreenUpdating = True 

End Sub 

폴더를 Chooing, 나는 스크립트에서 디렉토리를 작성하는 대신 현재 통합 문서의 셀에 "C7"에 삽입 된 디렉토리를 사용하고 싶습니다. 나는 대체하려고 :

strFolder = "C:\Users\user\Desktop\" 

strFolder = Dir(Range("C7").Value) 

로했지만 작동하지 않습니다. 어쩌면 누군가가 어떤 생각을 가지고 있을까요? 감사! 다음 ( C7에서) 및 디렉토리에

+0

워크 시트 ("wbName"). 범위 ("shName"). 범위 ("C7")' –

+0

기대되는 다른 것이 있을지 모르겠다. :하지만 내게 ID는 "있는 그대로"작동했습니다. C : \ Users \ tstracke \ Desktop \ U-Wert-Rechner \ test 문서에서 셀 21에 번호 21이 삽입되었습니다. 21은 지정된 폴더에있는 한 문서의 행 수입니다. –

+0

죄송합니다. 이해가 가지 않습니다. 내가 strFolder를 정확히 정의해야하는 방법은 무엇입니까? – Ale

답변

1

이 줄 strFolder = Dir(Range("C7").Value) 발견 firts 파일 변수 strFolder (예를 들어, C:\temp\somefile.txt)로이 파일의 경로를 기록합니다.

코드의 다음 줄 : strFile = Dir(strFolder & "*.xlsx")이이 경로를 사용하고 *.xlsx을 추가합니다. 결과적으로 당신은 strFile = Dir("C:\temp\somefile.txt*.xlsx")이 될 것이고 그것은 틀린 것입니다.

strFolder = Dir(Range("C7").Value) 
strFile = Dir(strFolder & "*.xlsx") 

다음 중 하나에 :

그래서,이 코드 변경 wsDest.Range("C7")

+1

고마워요! 'strFolder = Range ("C7"). Value'잘 작동합니다! :) – Ale

1

이 시도 : Btw는

strFolder = Range("C7").Value 
strFile = Dir(strFolder & "*.xlsx") 

을, 나는 당신이이 같은 Range("C7")을 위해 시트를 지정하는 것이 좋습니다 것

dim strPath as string 
strPath = CurDir + "NameofFile.xls" 
+0

고마워요, 제가 확인하겠습니다! – Ale

관련 문제