+ Reply to Thread
Results 1 to 46 of 46

Import Data

Hybrid View

  1. #1
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Import Data

    Hi,

    I have this VBA macro which imports data from a text file.
    I do not know exactly how to make it good.

    I have two sheets, named <INDATA> <Drawing_list>

    On sheet <Drawing_List> I made a command button with this code:

    Private Sub CommandButton1_Click()
    '
    ' Macro1 Macro
    ' Macro recorded 2/17/2008 by Hack
    '
    
    '
        
        With ActiveSheet.QueryTables.Add(Connection:= _
            "TEXT;H:\MyPath\test.txt", _
            Destination:=Range("A1"))
            .Name = "test.txt"
            .FieldNames = True
            .RowNumbers = True
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = True
            .RefreshStyle = xlOverwriteCells
            .SavePassword = False
            .SaveData = False
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = xlWindows
            .TextFileStartRow = 1
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = False
            .TextFileTabDelimiter = True
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = False
            .TextFileSpaceDelimiter = False
            .TextFileColumnDataTypes = Array(2)
            .Refresh BackgroundQuery:=False
        End With
    End Sub
    When I click it, it imports information from a textfile as you see.
    Allthough the information is printed out on sheet <Drawing_List> where the button is.
    I bet it has something to do with "With ActiveSheet" statement.
    I want the data from the textfile to be prionted in sheet <INDATA>.

    How?

    And my second question is how can this macro import data from all *.txt files under a certain path and print out the result in sheet <INDATA>
    In above case it's only one file.
    Is it like:
    "TEXT;H:\MyPath\*.txt", _
    .Name = "*.txt"

    My third question is relative paths. In my office we store project files in H:\Projectname\*.txt

    Projectname differs, so how can I make above code to:
    1. Read all text files in a specified fodler
    2. Put that data after eachother in sheet called <INDATA>
    3. Make the path to the specified folder "relative" due to project names are different

    Thanx

    This is liek my first attempt to modify the code above to my needs.

    best regards
    Last edited by au-s; 01-18-2010 at 08:36 AM.

  2. #2
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    Hi au-s
    This modified Andy Pope code may do the Trick
    Sub Macro1()
         '
         ' Macro1 Macro
         ' Macro  recorded 15/05/2006 by Andy Pope
         '
        Dim strPath As String
        Dim strFile As String
       
        strPath = "H:\MyPath\"
        strFile = Dir(strPath & "*.txt")
        Do While strFile <> ""
            With ActiveWorkbook.Worksheets("INDATA")
                With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
                    Destination:=.Cells(Rows.Count, 1).End(xlUp).Row)
                 .Parent.Name = Replace(strFile, ".txt", "")
                    .FieldNames = True
            .RowNumbers = True
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = True
            .RefreshStyle = xlOverwriteCells
            .SavePassword = False
            .SaveData = False
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = xlWindows
            .TextFileStartRow = 1
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = False
            .TextFileTabDelimiter = True
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = False
            .TextFileSpaceDelimiter = False
            .TextFileColumnDataTypes = Array(2)
            .Refresh BackgroundQuery:=False
    
                End With
            End With
            strFile = Dir
         Loop
         
    End Sub
    If the solution helped please donate to RSPCA

    Site worth visiting: Rabbitohs

  3. #3
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    Hi,

    That is strange.
    It runs okay if no text file is in that folder.
    Allthough when a textfile is there it gives me runtime error 13.

    When I search this rows output error
    With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
    Destination:=.Cells(Rows.Count, 1).End(xlUp).Row)

    thanx for help Sir

    Best Regards
    Last edited by shg; 01-14-2010 at 09:08 AM. Reason: deleted spurious quote

  4. #4
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    You wont need
     strPath &
    I'll have a close look this afternoon day as its 12:30pm here

  5. #5
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    Quote Originally Posted by pike View Post
    You wont need
     strPath &
    I'll have a close look this afternoon day as its 12:30pm here
    Any luck in testing?

  6. #6
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    This may be better
    what the dilemiter?
    Sub ptest()
        Dim b$, y$, p!, i$, k!, e
        b = "H:\MyPath\"
        k = ActiveWorkbook.Worksheets("INDATA").Cells(Rows.Count, 2).End(xlUp).Row
        ChDir b
        i = Dir("*.txt")
        Do While Len(i) > 0
            Open i For Input As #1
    
            Do Until EOF(1)
                p = 1
                Line Input #1, y
                With ActiveWorkbook.Worksheets("INDATA")
                    For Each e In Split(y, ",")
                        .Cells(Rows.Count, 1).End(xlUp).Offset(k, p) = e
                        p = 1 + p
                    Next
                    k = k + 1
                End With
            Loop
            Close #1
            i = Dir
        Loop
    End Sub

  7. #7
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    you will probally want to change this line
    For Each e In Split(y, ",")
    to
    For Each e In Split(y, vbTab)

  8. #8
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    Thank you Sir.

    That works okay. Very thankful for it.
    If I may ask you one more thing. Relative path.
    Right now the path needs to be exact. What if I want to make path such as:


    ..\..\Mypath
    or
    ..\..\..\Mypath

    So I can decide how relative it shall be. Is it possible?

    And where can I put the data:

    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(2)
    .Refresh BackgroundQuery:=False

    Thank you very much in advance.

    I am begining to catch up a bit with the code now ..
    Last edited by au-s; 01-18-2010 at 04:34 AM.

  9. #9
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    one way
    Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
    Declare Function SHBrowseForFolder Lib "shell32.dll" Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long
    Public Type BROWSEINFO: hOwner As Long: pidlRoot As Long: pszDisplayName As String: lpszTitle As String: ulFlags As Long: lpfn As Long: lParam As Long: iImage As Long: End Type
    
    
    Function DxfGetDirectory(Optional Msg) As String
    Dim bInfo  As BROWSEINFO, path$, r&, x&, pos%
    bInfo.pidlRoot = 0&
    If IsMissing(Msg) Then
    bInfo.lpszTitle = "Browse for a folder."
    Else: bInfo.lpszTitle = Msg
    End If
    bInfo.ulFlags = &H1
    x = SHBrowseForFolder(bInfo): path = Space$(512): r = SHGetPathFromIDList(ByVal x, ByVal path)
    If r Then
    pos = InStr(path, Chr$(0)): DxfGetDirectory = Left(path, pos - 1)
    Else: DxfGetDirectory = ""
    End If
    End Function
    
    Sub ptest()
        Dim b$, y$, p!, i$, k!, e
        b = DxfGetDirectory (Msg) &"\"
        k = ActiveWorkbook.Worksheets("INDATA").Cells(Rows.Count, 2).End(xlUp).Row
        ChDir b
        i = Dir("*.txt")
        Do While Len(i) > 0
            Open i For Input As #1
    
            Do Until EOF(1)
                p = 1
                Line Input #1, y
                With ActiveWorkbook.Worksheets("INDATA")
                    For Each e In Split(y, ",")
                        .Cells(Rows.Count, 1).End(xlUp).Offset(k, p) = e
                        p = 1 + p
                    Next
                    k = k + 1
                End With
            Loop
            Close #1
            i = Dir
        Loop
    End Sub
    Do you only want 2 columns?

  10. #10
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    One column is okay. It gives me one error about comments on the first line. of your above code. Declare function
    And that it overrite data all data.
    Thank you Sir
    Last edited by au-s; 01-18-2010 at 05:53 AM.

  11. #11
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    if its one column, it should be spliting, you have to find the correct delimiter
    either "," or vbtab or char(34) or " "
    there will be a couple to chose from. you can look by opening the csv in notebook

  12. #12
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    Quote Originally Posted by pike View Post
    if its one column, it should be spliting, you have to find the correct delimiter
    either "," or vbtab or char(34) or " "
    there will be a couple to chose from. you can look by opening the csv in notebook
    GOT IT!

    One more thing ...
    Public Type BROWSEINFO
    Gives me an error when I execute the "Function DxfGetDirectory" with the statemenet:
    Compilation error, can't define an own definied type which is Public in a object module ..

    That is translated from Swedish.

  13. #13
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    Hi au-s
    the top code must be the very first code up with option explicit

  14. #14
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    Allright, everytrhing works ...


    To overright data ... how can I make that code to overrite exisiting imoport and make formatting look like this:
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = True
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(2)
    .Refresh BackgroundQuery:=False

    All this formatting ... Where in the code shall that be placed ...

    ??
    Sorry for so many questions
    Last edited by au-s; 01-18-2010 at 07:13 AM.

  15. #15
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    I really should test this stuff first
    try this
    Option Explicit
    Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
    Declare Function SHBrowseForFolder Lib "shell32.dll" Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long
    Public Type BROWSEINFO: hOwner As Long: pidlRoot As Long: pszDisplayName As String: lpszTitle As String: ulFlags As Long: lpfn As Long: lParam As Long: iImage As Long: End Type
    Public msg
    
    Function DxfGetDirectory(Optional msg) As String
    Dim bInfo  As BROWSEINFO, path$, r&, x&, pos%
    bInfo.pidlRoot = 0&
    If IsMissing(msg) Then
    bInfo.lpszTitle = "Browse for a folder."
    Else: bInfo.lpszTitle = msg
    End If
    bInfo.ulFlags = &H1
    x = SHBrowseForFolder(bInfo): path = Space$(512): r = SHGetPathFromIDList(ByVal x, ByVal path)
    If r Then
    pos = InStr(path, Chr$(0)): DxfGetDirectory = Left(path, pos - 1)
    Else: DxfGetDirectory = ""
    End If
    End Function
    
    
    
    Private Sub CommandButton1_Click()
        Dim b$, y$, p!, i$, k!, e
        b = DxfGetDirectory(msg) & "\"
        k = ActiveWorkbook.Worksheets("INDATA").Cells(Rows.Count, 2).End(xlUp).Row
        ChDir b
        i = Dir("*.txt")
        Do While Len(i) > 0
            Open i For Input As #1
    
            Do Until EOF(1)
                p = 1
                Line Input #1, y
                With ActiveWorkbook.Worksheets("INDATA")
                    For Each e In Split(y, vbTab)
                        .Cells(Rows.Count, 1).End(xlUp).Offset(k, p) = e
                        p = 1 + p
                    Next
                    k = k + 1
                End With
            Loop
            Close #1
            i = Dir
        Loop
    End Sub

  16. #16
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    hey au-s
    we must be getting close how did it go or do we need a final fine tune?

  17. #17
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    Its working ....

    Allthough it si not overriting data. I want this to overrite data from the same textfile.
    So if it imports data from test.txt and test1.txt and I hit the button again it overrites.

    Now, it adds the same data again over and over again. Must buy you a smokey LAGAVULIN whiskey later on Sir

    Thanks!

  18. #18
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    Hey au-s
    replace
     k = ActiveWorkbook.Worksheets("INDATA").Cells(Rows.Count, 2).End(xlUp).Row
    with
         ActiveWorkbook.Worksheets("INDATA").Cells.ClearContents
        k =1
    should do it

  19. #19
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    Now it's perfect ...

    I will gradually learn this code now ..
    Are there any good webpages for explaining the vba macros in excel?

    Thank you very much for helping me in this issue

  20. #20
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    welcome the build in help files are good.In the code just highlight the word cells and press"F1" for an explaination

  21. #21
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    Hi again,

    Do not know why it happens but it does. This macro is okay allthough when I run
    Private Sub CommandButton1_Click()
    I often get the copy (as text) in the "data2" sheet of ALL Private Subs coded. So the whole code is typed out in data2 and not the data from the text files.
    So, it ignores the data in the textfiles and types the code instead in that sheet "data2".

    Sometimes when I deactivate macros and then activate them again it works.
    But mostly I need to do it all over again in a new workbook from scratch.

    I have to say that the Private Sub CommandButton1_Click() macro is in a Worksheet called Import.
    The Function you gave me with Option Explicit is as a module, Module1 so it is not in the Worksheet code but as a module.

    I have included my Worksheet ... It is all in Swedish But I think you will get the picture.
    Go to sheet "SkapaRitnings..." and look for
    Private Sub CommandButton1_Click()
    That is the button which has IMPORT FRAN CAD.

    Thanx

    PS
    If I remove Options Explicit, it usually start working.
    Attached Files Attached Files
    Last edited by au-s; 01-20-2010 at 06:29 AM.

  22. #22
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    Hey au-s
    I dont like to dont load any this over 20k on the wireless network
    So i had to wait till I had the glass wire connection to down load 134k

    anyway try this
    have moved the code back to the module and the button now call that sub
    Attached Files Attached Files

  23. #23
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    It still prints out the whole code....
    hehe ..

    Thing is that if I make some cosmetic or code change to it, it behaves strange ...
    Last edited by au-s; 01-21-2010 at 06:03 AM.

  24. #24
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    prints out the whole code?
    what do you mean?

  25. #25
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    I'll have to down load tomorrow and have a closer look
    so instead of printin the text file to the "INDATA" sheet it copies from the "data2".
    O mr au-s what have you dont

    just a famous add . it wont be much .. knew I should had down loaded a copy today.
    any who I will have a geeek tomorrow and reply

  26. #26
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    I mean by printing the whole code is that:
    In the sheet data2 where the data from the text files is imported it prints the code from the module vba-macro code and the sheet vba-macro code.


    This is what I sometimes get in the sheet data2 where the text file information should be:

    	Option Explicit		
    	Function DxfGetDirectory(Optional Msg) As String		
    	Dim bInfo  As BROWSEINFO, path$, r&, x&, pos%		
    	bInfo.pidlRoot = 0&		
    	If IsMissing(Msg) Then		
    	bInfo.lpszTitle = "Browse for a folder."		
    	Else: bInfo.lpszTitle = Msg		
    	End If		
    	bInfo.ulFlags = &H1		
    	x = SHBrowseForFolder(bInfo): path = Space$(512): r = SHGetPathFromIDList(ByVal x, ByVal path)		
    	If r Then		
    	pos = InStr(path, Chr$(0)): DxfGetDirectory = Left(path, pos - 1)		
    	Else: DxfGetDirectory = ""		
    	End If		
    	End Function		
    	Private Sub ComboBox1_Click()		
    	 Macro som läser in Skedesdata		
    	ActiveSheet.Shapes("ComboBox1").Select		
    	Selection.ListFillRange = "Komboboxdata!A1:A6"		
    	End Sub		
    	Private Sub ComboBox1_Change()		
    	 Macro som kopierar Skede till blad Utskrfift till en given cell		
    	Sheets("Utskrift").Range("F3").Value = ComboBox1.Value		
    	 End Sub		
    	Private Sub ComboBox2_Click()		
    	 Macro som läser in statusdata		
    	ActiveSheet.Shapes("ComboBox2").Select		
    	Selection.ListFillRange = "Komboboxdata!A8:A10"		
    	End Sub		
    	Private Sub ComboBox2_Change()		
    	 Macro som kopierar Skede till blad Utskrfift till en given cell		
    	Sheets("Utskrift").Range("F5").Value = ComboBox2.Value		
    	 End Sub		
    	Private Sub ComboBox3_Click()		
    	 Macro som läser in statusdata		
    	ActiveSheet.Shapes("ComboBox3").Select		
    	Selection.ListFillRange = "Komboboxdata!A12:A14"		
    	End Sub		
    	Private Sub ComboBox3_Change()		
    	Sheets("Utskrift").Range("B3").Value = ComboBox3.Value		
    	End Sub		
    	Sub CommandButton1_Click()		
    	Dim b$, y$, p!, i$, k!, e		
    	    b = DxfGetDirectory(Msg) & "\"		
    	    k = ActiveWorkbook.Worksheets("INDATA").Cells(Rows.Count, 2).End(xlUp).Row		
    	    ChDir b		
    	    i = Dir("*.txt")		
    	    Do While Len(i) > 0		
    	        Open i For Input As #1		
    	        Do Until EOF(1)		
    	            p = 1		
    	            Line Input #1, y		
    	            With ActiveWorkbook.Worksheets("INDATA")		
    	                For Each e In Split(y, ",")		
    	                    .Cells(Rows.Count, 1).End(xlUp).Offset(k, p) = e		
    	                    p = 1 + p		
    	                Next		
    	                k = k + 1		
    	            End With		
    	        Loop		
    	        Close #1		
    	        i = Dir		
    	    Loop		
    	End Sub		
    	Private Sub CommandButton2_Click()		
    	End Sub		
    	Private Sub TextBox1_Change()		
    	Sheets("Utskrift").Range("F8").Value = TextBox1.Value		
    	End Sub		
    	Private Sub TextBox2_Change()		
    	Sheets("Utskrift").Range("G8").Value = TextBox2.Value		
    	End Sub		
    	Private Sub TextBox3_Change()		
    	Sheets("Utskrift").Range("B1").Value = TextBox3.Value		
    	End Sub		
    	Private Sub TextBox4_Change()		
    	Sheets("Utskrift").Range("B2").Value = TextBox4.Value		
    	End Sub		
    	Private Sub TextBox5_Change()		
    	Sheets("Utskrift").Range("A8").Value = TextBox5.Value		
    	End Sub		
    	Private Sub TextBox6_Change()		
    	Sheets("Utskrift").Range("B8").Value = TextBox6.Value		
    	End Sub		
    	bfbh		
    		fbxcvb	
    	bxcv		
    	xcvbxcvb		
    			xvbn
    	Private Sub ComboBox1_Click()		
    	ComboBox1.DropDown		
    	End Sub		
    	Private Sub UserForm_Initialize()		
    	ComboBox1.AddItem "NOLLHANDLING"		
    	ComboBox1.AddItem "SYSTEMHANDLING"		
    	ComboBox1.AddItem "FÖRFRÅGNINGSUNDERLAG"		
    	ComboBox1.AddItem "BYGGLOVSHANDLING"		
    	ComboBox1.AddItem "BYGGHANDLING"		
    	End Sub		
    	Private Sub ComboBox1_Change()		
    	Select Case ComboBox1.Value		
    	Case "NOLLHANDLING"		
    	Selection.Copy		
    	Range("A1").Select		
    	ActiveSheet.Paste		
    	Case "SYSTEMHANDLING"		
    	Selection.Copy		
    	Range("A1").Select		
    	ActiveSheet.Paste		
    	Case "FÖRFRÅGNINGSUNDERLAG"		
    	Selection.Copy		
    	Range("A1").Select		
    	ActiveSheet.Paste		
    	Case "BYGGLOVSHANDLING"		
    	Selection.Copy		
    	Range("A1").Select		
    	ActiveSheet.Paste		
    	Case "BYGGHANDLING"		
    	Selection.Copy		
    	Range("A1").Select		
    	ActiveSheet.Paste		
    	End Select		
    	Sheets("12").Select		
    	Range("A1").Value = ComboBox1.Value		
    	End Sub
    This is the entire vba-macro code

    It seems it happens somtimes when I mix with the code a bit. For example when I added DeleteRows Sub.
    For some reason now it is working correctly so far ..

  27. #27
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    with the changes i made this morning?

  28. #28
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    .. and now it dont

  29. #29
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    yes, with your changes
    It worked but now it suddenly stopped working

  30. #30
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    Now it works again ...
    I just don't have a clue why it happens. What I did now was to set the file Read-Only.
    I made a change. It is really sensitive to changes, whatever they might be

  31. #31
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    the posted code looks OK
    I'll take a closer look tomorrow. Its strange its reading the sheet module code to the work sheet?
    there is heap we can do to make it run smoth for example remove the "select" and replace then with "With" syntax ect...

  32. #32
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    Yeah ...
    I found something similiar maybe for you top take a look at...
    http://www.excelforum.com/excel-prog...ext-files.html

    Here they are exporting certain lines and I just want to export it all

  33. #33
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    hHi au-s
    try this code for module one

    Option Explicit
    Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
    Declare Function SHBrowseForFolder Lib "shell32.dll" Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long
    Public Type BROWSEINFO: hOwner As Long: pidlRoot As Long: pszDisplayName As String: lpszTitle As String: ulFlags As Long: lpfn As Long: lParam As Long: iImage As Long: End Type
    Public msg
    
    
    Function DxfGetDirectory(Optional msg) As String
    Dim bInfo  As BROWSEINFO, path$, r&, x&, pos%
    bInfo.pidlRoot = 0&
    If IsMissing(msg) Then
    bInfo.lpszTitle = "VÄLJ PROJEKTMAPP!"
    Else: bInfo.lpszTitle = msg
    End If
    bInfo.ulFlags = &H1
    x = SHBrowseForFolder(bInfo): path = Space$(512): r = SHGetPathFromIDList(ByVal x, ByVal path)
    If r Then
    pos = InStr(path, Chr$(0)): DxfGetDirectory = Left(path, pos - 1)
    Else: DxfGetDirectory = "VÄLJ PROJEKTMAPP!"
    End If
    End Function
    
     Sub thisOne()
        Dim b$, y$, p!, i$, k!, e
        b = DxfGetDirectory(msg) ' & "\A\Admin-IT\Attribut\Export\Förteckningar\Ritnings\"
             ActiveWorkbook.Worksheets("data2").Cells.ClearContents
        k = 1
        ChDir b
        i = Dir("*.txt")
        Do While Len(i) > 0
            Open i For Input As #1
    
            Do Until EOF(1)
                p = 1
                Line Input #1, y
                With ActiveWorkbook.Worksheets("data2")
                    For Each e In Split(y, vbTab)
                        .Cells(Rows.Count, 1).End(xlUp).Offset(k, p) = e
                        p = 1 + p
                    Next
                    k = k + 1
                End With
            Loop
            Close #1
            i = Dir
        Loop
        ' Delete blank Rows see module 2
        DeleteBlankRows
    End Sub
    dont know what this bit is about but I removed Rem
    ' & "\A\Admin-IT\Attribut\Export\Förteckningar\Ritnings\"

  34. #34
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    and
    change this
    Function DxfGetDirectory(Optional msg) As String
    Dim bInfo  As BROWSEINFO, path$, r&, x&, pos%
    bInfo.pidlRoot = 0&
    If IsMissing(msg) Then
    bInfo.lpszTitle = "VÄLJ PROJEKTMAPP!"
    Else: bInfo.lpszTitle = msg
    End If
    bInfo.ulFlags = &H1
    x = SHBrowseForFolder(bInfo): path = Space$(512): r = SHGetPathFromIDList(ByVal x, ByVal path)
    If r Then
    pos = InStr(path, Chr$(0)): DxfGetDirectory = Left(path, pos - 1)
    Else: DxfGetDirectory =""   ' This bit back to "" what is "VÄLJ PROJEKTMAPP!"
    End If
    End Function
    what is "VÄLJ PROJEKTMAPP!"
    I have a copy now so lets fine tune away

  35. #35
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    This bit that you describe is :
    If I choose a certain path for example
    U:\p-r-s\project1
    the rest of the path is added, meaning "A\Admin-IT\Attribut\Export\Förteckningar\Ritnings"

    I thought I could do so.
    Since our projects are sorted like:
    U:\a-b-c\Cproject1
    U:\d-e-f\FProject12

    The first path is different but after Project name the path is always the same, hence the added path.
    So I thought I could make the code to look for a path chosen y the user which is the path to the project name and then since the path is always the same under each project it will always look for text files there.

    It maybe was not that smart.

    VÄL PROJEKTMAPP means in Swedish Browse for Project folder.

  36. #36
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    Hi au-s
    We can change the way you pick the path .If that is the case maybe a combobox in a userform will be better?

  37. #37
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    Yes. Give it a try ...
    It might be a good solution Sir.

  38. #38
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    Hi au-s
    Have a go at creating a userform and add a combobox ect..
    I'll help you work with what you come up with

  39. #39
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    Right,

    But can' the path just be \Admin-IT\Attribut\Export\Förteckningar\Ritnings\
    Does the path needs to be absolute?

    I mean if you have:
    Private Const ExportPath  As String = "Admin-IT\Attribut\Export\Förteckningar\Ritnings\"
    Then the above code is the path.
    The projects absolute path is:
    U:\j-k-l\Lproject

    Path to thextfiels is:
    U:\j-k-l\Lproject\A\Admin-IT\Attribut\Export\Förteckningar\Ritnings\*.txt

    Path to excelfile is:
    U:\j-k-l\Lproject\A\Dokument\08_Forteckningar\exelfile.xls


    Second solution is if I make a comboBox I do not know exactly how I can solve it with a drop down.
    The best solution then is to have a TextBox where you type the first path as a string and then the rest of the path is just added in the function?
    Last edited by au-s; 01-22-2010 at 04:41 AM.

  40. #40
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    I made something like that:

    Option Explicit
    Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
    Declare Function SHBrowseForFolder Lib "shell32.dll" Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long
    Public Type BROWSEINFO: hOwner As Long: pidlRoot As Long: pszDisplayName As String: lpszTitle As String: ulFlags As Long: lpfn As Long: lParam As Long: iImage As Long: End Type
    Private Const ExportPath As String = "\A\Admin-IT\Attribut\Export\Förteckningar\Ritnings\"
    Public msg
    
    
    Function DxfGetDirectory(Optional msg) As String
    Dim bInfo  As BROWSEINFO, path$, r&, x&, pos%
    bInfo.pidlRoot = 0&
    If IsMissing(msg) Then
    bInfo.lpszTitle = "Browse for folder."
    Else: bInfo.lpszTitle = msg
    End If
    bInfo.ulFlags = &H1
    x = SHBrowseForFolder(bInfo): path = Space$(512): r = SHGetPathFromIDList(ByVal x, ByVal path)
    If r Then
    pos = InStr(path, Chr$(0)): DxfGetDirectory = Left(path, pos - 1)
    Else: DxfGetDirectory = ""
    End If
    End Function
    
     Sub thisOne()
         Dim AbsolutExportRitningsfrtPath As String
        
        AbsolutExportRitningsfrtPath = DxfGetDirectory(msg) & ExportPath
        Dim b$, y$, p!, i$, k!, e
       
             ActiveWorkbook.Worksheets("data2").Cells.ClearContents
             k = 1
        ChDir AbsolutExportRitningsfrtPath
        i = Dir("*.txt")
        Do While Len(i) > 0
            Open i For Input As #1
    
            Do Until EOF(1)
                p = 1
                Line Input #1, y
                With ActiveWorkbook.Worksheets("data2")
                    For Each e In Split(y, vbTab)
                        .Cells(Rows.Count, 1).End(xlUp).Offset(k, p) = e
                        p = 1 + p
                    Next
                    k = k + 1
                End With
            Loop
            Close #1
            i = Dir
        Loop
        ' Delete blank Rows see module 2
        DeleteBlankRows
        MsgBox ("Importen är KLAR!")
    End Sub
    I made changes to
    added Private Const ExportPath
    and
    in the Sub code:
    Dim AbsolutExportRitningsfrtPath As String


    Look also on the Sub code if it is correct ...

    Seems to work now as well but it copies the code sometimes I have noticed again.
    Last edited by au-s; 01-22-2010 at 05:05 AM.

  41. #41
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    hi au-s
    what I was thinking was replace this with
     b = DxfGetDirectory(msg) ' & "\A\Admin-IT\Attribut\Export\Förteckningar\Ritnings\"
             ActiveWorkbook.Worksheets("data2").Cells.ClearContents
        k = 1
    with
    userform1.show
    b = "U:\j-k-l\Lproject\" & combox1.value & \"
             ActiveWorkbook.Worksheets("data2").Cells.ClearContents
     unload userform1
       k = 1
    and userform code
    Private Sub CommandButton1_Click()
    
    UserForm1.Hide
    End Sub
    
    Private Sub UserForm_Initialize()
    With ComboBox1
    .List = Array("Admin-IT\Attribut\Export\Förteckningar\Ritnings\", "what ever", "and again", "more stuff", "u")
    End With
    End Sub
    if you are use changing folders

  42. #42
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    Okay, I will try this.

  43. #43
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    The problem here is that the user can't change the path to the project?

    Anyways I dont think that the problem lies within the code itself.
    Cause it sometimes work, sometimes it doesnt.
    I think it is Gods POWAH!

  44. #44
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    thats ONLY if the first part of the path is constant
    if its the second part thats constant you will have to revert to the original code
    and complete the whole path
    you just cant pick one bit unless it the end

    with the original code I couldnt make it do the same as you

  45. #45
    Registered User
    Join Date
    01-14-2010
    Location
    Stockholm
    MS-Off Ver
    Excel 2003
    Posts
    24

    Re: Import Data

    YEah,

    I think looking at this code is that you have ChDir AbsolutExportRitningsfrtPath ...
    If I make a new Sub

     Sub Path()
     
         Dim AbsolutExportRitningsfrtPath As String
        
        AbsolutExportRitningsfrtPath = DxfGetDirectory(msg) & ExportPath
     End Sub
    Instead of having the Sub ThisOne () changing to the dir wit hChDir, can the Sub Path() be somehow implemented in the Sub ThisOne () and do the rest?

    I am being annoying SORRY

  46. #46
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Import Data

    No not at all
    As long as you have something to work with and are willing to have a go we can go down in history as the longest post ever! but we have a long long long way to go before that.
    I like to solve the puzzles

    yes maybe, but you would have to pull up short of the full path! one folder to many and you will create an error as the path wont exist
    worth a try..

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1