VBA를 사용하여 두 쉼표 사이의 값 얻기

VBA를 사용하여 두 쉼표 사이의 값 얻기

Excel 데이터를 이용하여 텍스트 파일을 편집하고 싶습니다. 텍스트 파일의 형식은 다음과 같습니다.

Data1, Number1, Number2, ..., etc.

Number1합계 값(숫자 1+엑셀 데이터)을 가져와서 바꾸고 싶습니다 . Number2역시 같은 흐름이다.

이를 수행하는 가장 좋은 방법은 무엇입니까?

답변1

이 샘플은 텍스트 파일을 읽고 쉼표 사이의 모든 값을 가져와 셀 A1의 값과 합산합니다.100

입력 파일(C:\test.txt)

data1,1,2,3,4,5
data2,1,2,3,4,5

엑셀 데이터(시트 1)

[A1] = 100

암호

Sub ReadCommas()

    strPath = "C:\test.txt"
    Dim arVal() As String

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set objFile = fso.OpenTextFile(strPath)

    Do While Not objFile.AtEndOfStream
        strLine = objFile.ReadLine
        arVal = Split(strLine, ",")

        For i = 1 To UBound(arVal)
            arVal(i) = Val(arVal(i)) + Sheets(1).Cells(1, 1)
            Debug.Print arVal(i)
        Next i

    Loop
    objFile.Close

End Sub

산출(VBA 편집기 » 직접 실행 창)

101
102
103
104
105
201
202
203
204
205

답변2

다음 코드에서 원하는 대로 Number1과 Number2 값을 얻었습니다.

입력 파일(C:\intest.txt)

Data1, 1, 2, ...etc
Data2, 3, 4, ...etc
...  
Data100, 200, 300, ...etc

Excel 데이터(시트 1)

[A1] = 100, [B1] = 200
[A2] = 300, [B2] = 400
...  
[A100] = 2000, [B100] = 3000

암호

Sub ButtonClick()

    strPath = "C:\intest.txt"    

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set objFile = fso.OpenTextFile(strPath)

    Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine        
        '※1 means Start Position of Num1
        intNum1Cnt = (InStr(※1, strLine, ",")) - ※1    'Count of Number1 of Data1:1
        dblNum1 = Mid(strLine , ※1, intNum1Cnt )        'Value of Number1 of Data1:1
        dblExcelNum1 = GetValue1()                       'Value of [A1]:100
        dblSumNum1 = dblNum1 + dblExcelNum1              'Sum:101
        'Replace dblSumNum1 to dblNum1 in OutputFile

        '※2 means Start Position of Num2
        ※2 = ※1 + intValue1Cnt + 1
        intNum2Cnt = InStr(※2, strLine, ",") - ※2       'Count of Number2 of Data1:1
        dblNum2 = Mid(strLine, ※2, intNum2Cnt)           'Value of Number2 of Data1:2
        dblExcelNum2 = GetValue2()                        'Value of [B1]:200            
        dblSumNum2 = dblNum2 + dblExcelNum2               'Sum:202
        'Replace dblSumNum2 to dblNum2 in OutputFile    
    Loop
    objFile.Close
End Sub


Function GetValue1() As Double

    For i = 1 To 100
        strCellValue1 = Sheets(1).Cells(i, 1).Value
        GetValue1 = CDbl(strCellValue1)            
    Next i  
End Function


Function GetValue2() As Double

    For j = 1 To 100
        strCellValue2 = Sheets(1).Cells(j, 2).Value
        GetValue2 = CDbl(strCellValue2)            
    Next j  
End Function

출력 파일(C:\outtest.txt)

Data1, 101, 202, ...etc
Data2, 303, 404, ...etc
...  
Data100, 2200, 3300, ...etc

관련 정보