Sobreposição de conteúdo durante a importação de dados

1

Estou fazendo um projeto usando o Excel VBA, mas tenho um problema ao importar dados. Toda vez que eu importo dados, ele se sobrepõe à coluna existente.

Alguém pode me ajudar a resolver esse problema, abaixo está o código.

Private Sub CommandButton1_Click()

Dim myFile As String, text As String, textline As String, Name As Integer, Phone As Integer, Address1 As Integer, Dated As Integer
Dim Email As Integer, Postcode As Integer, SR As Integer, MTM As Integer, Serial As Integer, Problem As Integer, Action As Integer


myFile = "C:\Users\test.txt"


Open myFile For Input As #1
    Do Until EOF(1)
        Line Input #1, textline
        text = text & textline
    Loop
Close #1

Name = InStr(text, "Name")
Phone = InStr(text, "Phone")
Address1 = InStr(text, "Address1")
Email = InStr(text, "Email")
Postcode = InStr(text, "Postcode")
SR = InStr(text, "SR")
MTM = InStr(text, "MTM")
Serial = InStr(text, "Serial")
Problem = InStr(text, "Problem")
Action = InStr(text, "Action")
Dated = InStr(text, "Dated")


Range("C11").Value = Mid(text, Name + 6, 15)
Range("H13").Value = Mid(text, Phone + 6, 8)
Range("C15").Value = Mid(text, Address1 + 9, 25)
Range("C13").Value = Mid(text, Email + 6, 15)
Range("H16").Value = Mid(text, Postcode + 9, 5)
Range("C10").Value = Mid(text, SR + 4, 8)
Range("H14").Value = Mid(text, MTM + 5, 8)
Range("H15").Value = Mid(text, Serial + 8, 9)
Range("C17").Value = Mid(text, Problem + 9, 15)
Range("C18").Value = Mid(text, Action + 7, 10)
Range("H10").Value = Mid(text, Dated + 7, 10)

End Sub

Encontre os dados na folha anexa. O telefone pula para o nome da coluna o mesmo se aplica a outras colunas. Dados em H13 está chegando ao C11 da mesma forma outros.

.

Editar

OiPaul,aindaestoutendoproblemacomimpressãoeconversãodafolhaparaPDF.

Semusaroprimeiroouosegundocódigo,possoexecutaroscódigosabaixoenafolhaparaPDF,masagora,depoisdeexecutaroprimeiroeosegundocódigos,oscódigosabaixonãopodemconverterafolhaemPDF...Icontinuerecebendo"erro definido pelo aplicativo ou definido pelo objeto" e erro de tempo de execução '1004' Documento não salvo. o documento pode estar aberto ou pode ter encontrado um erro ao salvar ..

Posso saber o que há de errado com meu código?

Private Sub CommandButton2_Click()
    Dim FilePath As String
    Dim FileName As String
    Dim MyDate As String
    Dim report As String
    Dim Name As String

    FilePath = "C:\Users\Documents\test\"
    MyDate = Format(Date, " - MM-DD-YYYY")
    report = " - Quatation"
    Name = Worksheets("Sheet1").Range("C10")

    Sheets("Sheet1").Range("A1:I60").ExportAsFixedFormat Type:=xlTypePDF, _
        FileName:=FilePath & Name & MyDate & report
End Sub
Private Sub report()
    Dim myFile As String, lastRow As Long
    myFile = "C:\Users\Documents\test\" & Sheets("Sheet1").Range("C11") & "_" & Sheets("Sheet1").Range("C17") & Format(Now(), "yyyy-mm-dd") & ".pdf"
    lastRow = Sheets("Sheet3").UsedRange.SpecialCells(xlCellTypeLastCell).Row + 1
    'Transfer data to sheet3
    Sheets("Sheet3").Cells(lastRow, 1) = Sheets("Sheet1").Range("C11")
    Sheets("Sheet3").Cells(lastRow, 2) = Sheets("Sheet1").Range("C17")
    Sheets("Sheet3").Cells(lastRow, 3) = Sheets("sheet1").Range("I28")
    Sheets("Sheet3").Cells(lastRow, 4) = Now
    Sheets("Sheet3").Hyperlinks.Add Anchor:=Sheets("Sheet3").Cells(lastRow, 5), Address:=myFile, TextToDisplay:=myFile
    'Create invoice in PDF format
    Sheets("sheet1").ExportAsFixedFormat Type:=xlTypePDF, FileName:=myFile
    Application.DisplayAlerts = False
    'create invoice in XLSX format
    ActiveWorkbook.SaveAs "C:\Users\Documents\test\" & Sheets("Sheet1").Range("C11") & "_" & Sheets("Sheet1").Range("C17") & "_" & Format(Now(), "yyyy-mm-dd") & ".xlsx", FileFormat:=51
    'ActiveWorkbook.Close
    Application.DisplayAlerts = True
End Sub

    
por gist102 11.06.2018 / 09:46

1 resposta

2

Você pode tornar o código mais eficiente, sustentável e um pouco mais dinâmico

As duas versões abaixo determinam o tamanho dos dados com base na localização do próximo token ( "Phone" )
em relação ao token atual ( "Name" )

.

A versão 1 usa matrizes para mapear tokens para células diferentes em Sheet5

Option Explicit

Private Sub CommandButton1_Click()

    Const FULL_PATH = "C:\Users\test1.txt"

    Const TOKENS = "Name Phone Address1 Email Postcode SR MTM Serial Problem Action Dated"
    Const LOCATIONS = "C11 H13 C15 C13 H16 C10 H14 H15 C17 C18 H10"

    Dim fId As String, txt As String, txtLen As Long, idArr As Variant, locArr As Variant

    fId = FreeFile
    Open FULL_PATH For Input As fId
        txt = Input(LOF(fId), fId)  'Read entire file (not line-by-line)
    Close fId
    txtLen = Len(txt)

    idArr = Split(TOKENS)
    locArr = Split(LOCATIONS)

    Dim i As Long, k As String, sz As Long, found As Long, ub As Long

    ub = UBound(idArr)

    With ThisWorkbook.Worksheets("Sheet5")     '<--- Update sheet name
        For i = LBound(idArr) To ub
            k = idArr(i)        'Name, Phone, etc
            found = InStr(txt, k) + Len(k) + 1  'Find current key in file
            If found > 0 Then   'Determine item length by finding the next key
                If i < ub Then sz = InStr(txt, idArr(i + 1)) Else sz = txtLen + 2
                .Range(locArr(i)).Value2 = Trim$(Mid$(txt, found, sz - found - 1))
            End If
        Next
    End With
End Sub

.

Versão 2 usa um dicionário

Private Sub CommandButton1_Click()
    Const FULL_PATH = "C:\Users\test2.txt"
    Dim fId As String, txt As String, txtLen As Long, d As Object, dc As Long

    fId = FreeFile
    Open FULL_PATH For Input As fId
        txt = Input(LOF(fId), fId)  'Read entire file (not line-by-line)
    Close fId
    txtLen = Len(txt)
    Set d = CreateObject("Scripting.Dictionary")
    d("Name") = "C11"   'Same as: d.Add Key:="Name", Item:="C11"
    d("Phone") = "H13"
    d("Address1") = "C15"
    d("Email") = "C13"
    d("Postcode") = "H16"
    d("SR") = "C10"
    d("MTM") = "H14"
    d("Serial") = "H15"
    d("Problem") = "C17"
    d("Action") = "C18"
    d("Dated") = "H10"
    dc = d.Count

    Dim i As Long, k As String, sz As Long, found As Long
    With ThisWorkbook.Worksheets("Sheet5")     '<--- Update sheet name
        For i = 0 To dc - 1     'd.Keys()(i) is a 0-based array
            k = d.Keys()(i)     'Name, Phone, etc
            found = InStr(txt, k) + Len(k) + 1  'Find the (first) key in file
            If found > 0 Then   'Determine item length by finding the next key
                If i < dc - 1 Then sz = InStr(txt, d.Keys()(i + 1)) Else sz = txtLen + 2
                .Range(d(k)).Value2 = Trim$(Mid$(txt, found, sz - found - 1))
            End If
        Next
    End With
End Sub

.

test1.txt

Name Name1
Phone Phone1
Address1 Address11
Email Email1
Postcode Postcode1
SR SR1
MTM MTM1
Serial Serial1
Problem Problem1
Action Action1
Dated Dated1

Resultado 1 :

.

test2.txt

NameName2PhonePhone2Address1Address12EmailEmail2PostcodePostcode2SRSR2MTMMTM2SerialSerial2ProblemProblem2ActionAction2DatedDated2

Resultado2:

por 12.06.2018 / 03:22