Run time error Library not registered while opening a .doc file - vba

I created a macro in excel vba to process a list of file that I need to copy from a "source path" to a "target path". When copied I also need to remove the protection of the .doc file.
Everything is working perfectly fine but only on my station. When I try it on two others stations I get the following error message:
"Run time error '2147319779 (8002801d)'
Automation error
Library not registered"
Here's what I already checked: I've checked for the VBA references in Excel and Word and they are the same.
From what I can found on other forums it could be some hexkeys problem, but I'm so afraid of playing into this, and also the solution that was proposed wasn't working (I couldn't find the appropriate reg key on the problem station).
I also tried adding some delay, but still no luck
Here's my code below
Sub copy_file_and_unprotect()
Dim ws As Worksheet
Dim wb As Workbook
Dim original_name As String
Dim copied_name As String
Dim WdApp As Object
Dim source_path As String
Dim target_path As String
Dim pwd As String
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Liste de vérification") 'where the original folder is stored
target_path = ws.Cells(1, 6) & "\Sections de devis type"
Set ws = wb.Worksheets("Nom des divisions")
source_path = ws.Cells(4, 5) 'where the file will be copied
pwd = "cimaqc123" 'password to unprotect the file
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Plan de travail")
lig = 11
col = 26
Set WdApp = CreateObject("Word.Application")
While ws.Cells(lig, col) <> "" 'loop to copy & unprotect a list of file
num_sec = ws.Cells(lig, col)
nom_sec = ws.Cells(lig, col + 2)
file_name = num_sec & " - " & nom_sec & ".doc" 'name of the original file to be copied
F = Dir(source_path & "\" & "*.doc") 'loop to search thru the source file for the file "file_name"
Do While Len(F) > 0
If F = file_name Then '
original_name = source_path & "\" & F 'path and name of file to be copied
copied_name = target_path & "\" & file_name 'path and name of new file to be unlocked later on
FileCopy original_name, copied_name 'copying of the file
'-----THIS IS WHERE I GET THE ERROR MESSAGE AFTER THE FOLLOWING LINE-----
Set WdApp = Documents.Open(copied_name)
If Not WdApp.ProtectionType = -1 Then 'unprotect the file
WdApp.Unprotect pwd
WdApp.Close True
Else
WdApp.Close True
End If
GoTo file_copied:
End If
F = Dir()
Loop
file_copied:
lig = lig + 1 'on passe à la prochaine section de devis
Wend
End Sub
Could anyone share some taughts about this? How can I resolve the error message I get?

With the help from #KenWhite here's the updated code with error resolved
Sub copy_file_and_unprotect()
Dim ws As Worksheet
Dim wb As Workbook
Dim original_name As String
Dim copied_name As String
Dim WdApp As Object
Dim WdDoc As Object
Dim source_path As String
Dim target_path As String
Dim pwd As String
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Liste de vérification") 'where the original folder is stored
target_path = ws.Cells(1, 6) & "\Sections de devis type"
Set ws = wb.Worksheets("Nom des divisions")
source_path = ws.Cells(4, 5) 'where the file will be copied
pwd = "cimaqc123" 'password to unprotect the file
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Plan de travail")
lig = 11
col = 26
Set WdApp = CreateObject("Word.Application")
While ws.Cells(lig, col) <> "" 'loop to copy & unprotect a list of file
num_sec = ws.Cells(lig, col)
nom_sec = ws.Cells(lig, col + 2)
file_name = num_sec & " - " & nom_sec & ".doc" 'name of the original file to be copied
F = Dir(source_path & "\" & "*.doc") 'loop to search thru the source file for the file "file_name"
Do While Len(F) > 0
If F = file_name Then '
original_name = source_path & "\" & F 'path and name of file to be copied
copied_name = target_path & "\" & file_name 'path and name of new file to be unlocked later on
FileCopy original_name, copied_name 'copying of the file
'----------------LINE BELOW IS WHERE IT WAS CAUSING PROBLEM -------------------------
Set WdDoc = WdApp.Documents.Open(copied_name) 'line that was add
'Set WdApp = Documents.Open(copied_name) 'line that was removed
If Not WdDoc.ProtectionType = -1 Then 'unprotect the file
WdDoc.Unprotect pwd 'replaced WdApp by WdDoc
WdDoc.Save
WdDoc.Close True
Else
WdDoc.Close True
End If
GoTo file_copied:
End If
F = Dir()
Loop
file_copied:
lig = lig + 1
Wend
End Sub

Related

VBA macro to find Sheet count in a directory

I'm not good with VBA at all but I was curious to know if there is a way to count the amount of worksheets in a workbook that's looped for all the files in a folder.
For example, A1 list the file names and B1 shows the count of sheets.
A1 B1
book1 5
book2 6
currently have this code set up and need to adjust it
Sub ListAllFile()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim ws As Worksheet
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ws = Worksheets.Add
Set objFolder = objFSO.GetFolder("W:\101g-19 (4.20.18) - Copy\")
ws.Cells(1, 1).Value = "The files found in " & objFolder.Name & " are:"
For Each objFile In objFolder.Files
ws.Cells(ws.UsedRange.Rows.Count + 1, 1).Value = objFile.Name
'ADD A WORKSHEET AND PASTE "=SHEETS()" in A1 the copy value of a1 in to list
'close files with out saving
Next
Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing
End Sub
Take a look at the below - note that you should run this from inside of a blank worksheet
Set CurrentWB = ActiveWorkbook
Dim folderPath As String
Dim Filename As String
Dim wb As Workbook
Dim J As Long
Dim N As Long
Dim lc As Long
Dim lr As Long
'UPDATE FOLDER PATH OF WHERE XLS FILES ARE LOCATED
folderPath = "C:\Users\username\Desktop\test\" 'change to suit
J = 2
' Column Headers
CurrentWB.Sheets(1).Range("A1").Value = "Filename"
CurrentWB.Sheets(1).Range("B1").Value = "# of Sheets"
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
'YOU CAN CHANGE TO BE ANY FILE TYPE BUT CURRENTLY SET TO .XLSX
Filename = Dir(folderPath & "*.xlsx")
Do While Filename <> ""
Application.ScreenUpdating = False
Set TempWB = Workbooks.Open(folderPath & Filename)
' Counts Per Worksheet
N = ActiveWorkbook.Worksheets.Count
CurrentWB.Sheets(1).Range("A" & J).Formula = Filename
CurrentWB.Sheets(1).Range("B" & J).Formula = N
' Close Temporary Workbook
TempWB.Close False
J = J + 1
Filename = Dir
Loop
In your for loop, open the file (assuming they are all excel here) and get the count of worksheets.
Something like:
For Each objFile In objFolder.Files
writeCell = ws.Cells(ws.UsedRange.Rows.Count + 1, 1)
writeCell.Value = objFile.Name
'ADD A WORKSHEET AND PASTE "=SHEETS()" in A1 the copy value of a1 in to list
'close files with out saving
Set wb = Workbooks.Open(objFile.Name)
writeCell.Offset(,1).value = wb.Worksheets.Count()
wb.Close(false)
Next
Sub ListallFiles()
Dim sFileName As String
Dim sFolderPath As String: sFolderPath = "C:\Temp\" ' Change folder path. Ensure that folder path ends with "\"
Dim oWB As Workbook
Dim oWS As Worksheet
' Get the first excel file name from specified folder
sFileName = Dir(sFolderPath & "*.xls*")
' Add a worksheet
Set oWS = ThisWorkbook.Worksheets.Add
With oWS
' Set folder name in the new sheet
.Range("A1").Value = "The file found in " & sFolderPath & " are:"
' Loop through all excel files in the specified folder
Do While Len(Trim(sFileName)) > 0
' Open workbook
Set oWB = Workbooks.Open(sFolderPath & sFileName)
' Set workbook details in the file
.Range("A" & .Cells(.Rows.Count, "A").End(xlUp).Row + 1).Value = sFileName
.Range("B" & .Cells(.Rows.Count, "B").End(xlUp).Row + 1).Value = oWB.Worksheets.Count
' Close workbook
oWB.Close False
' Clear workbook object
Set oWB = Nothing
' Get next excel file
sFileName = Dir()
Loop
End With
End Sub
Above UDF should open all files in the specified folder and give you the number of worksheets in each workbook on a new worksheet

Rename Sheet after it is copied and Create Master Workbook

Below is code used to copy sheets from source and then rename and place into a destination.
I would like to extend the functionality to use another cell reference to rename the Sheet Name in the newly created file. (Note each copied workbook will only have one sheet.) Then after all the workbooks are copied, renamed, and sheets renamed, merge all the workbooks in the destination path into one.
Sub CopyRenameFile()
Dim src As String, dst As String, fl As String, f2 As String
Dim rfl As String
Dim rf2 As String
'Source directory
src = Range("B3")
'Destination directory
dst = Range("D3")
'File name
fl = Range("B6")
f2 = Range("B7")
'Rename file
rfl = Range("D6")
rf2 = Range("D7")
On Error Resume Next
FileCopy src & "\" & fl, dst & "\" & rfl
FileCopy src & "\" & f2, dst & "\" & rf2
If Err.Number <> 0 Then
MsgBox "Copy error: " & src & "\" & rfl
End If
On Error GoTo 0
Dim xL As Excel.Application
Set xL = New Excel.Application
xL.Visible = True
Dim wb As Excel.Workbook
Set wb = xL.Workbooks.Open(F6)
'In case you don't know how here are two ways to reference a sheet:
Dim sh As Excel.Worksheet
Set sh = xL.Sheets(1)
sh.Name = "TestMeOut"
'Saving and closing are important...
wb.Save
Set wb = Nothing
xL.Quit
Set xL = Nothing
End Sub
If it's the active sheet, use
ActiveSheet.Name = "New Name"
If it isn't the active sheet then use:
Sheets("SheetName").Name = "New Name"
or
Sheets(2).Name = "New Name"
for the last one, the index (2 in the example) is the sheet number counting from left to right starting at 1.
To open an Excel workbook by filename:
Dim xL As Excel.Application
Set xL = New Excel.Application
xL.Visible = True
Dim wb as Excel.Workbook
Set wb = xl.Workbooks.Open(put your filename here as a literal or variable)
'In case you don't know how here are two ways to reference a sheet:
Dim sh As Excel.Worksheet
Set sh = xL.Sheets("Sheet1")
' or
Set sh = xL.Sheets(1)
'put your code here
'Saving and closing are important...
wb.Save
Set wb = Nothing
xL.Quit
Set xL = Nothing
NOTE: to use the Excel references, go to Tool => References and look for the Microsoft Office xx.x Object Library (where xx.x is the version).

Open all dbf files in a folder and save them as excel in another folder

I have a folder "test" containing several dbf files. I would like vba to open them in excel file and save them (in excel format) in another folder keeping the same dbf file names.
I found this code on the net and am trying to use this code for my needs but it won't work. Error message:
"sub of function not defined"
...please look into it.
Sub test()
Dim YourDirectory As String
Dim YourFileType As String
Dim LoadDirFileList As Variant
Dim ActiveFile As String
Dim FileCounter As Integer
Dim NewWb As Workbook
YourDirectory = "c:\Users\navin\Desktop\test\"
YourFileType = "dbf"
LoadDirFileList = GetFileList(YourDirectory)
If IsArray(LoadDirFileList) = False Then
MsgBox "No files found"
Exit Sub
Else
' Loop around each file in your directory
For FileCounter = LBound(LoadDirFileList) To UBound(LoadDirFileList)
ActiveFile = LoadDirFileList(FileCounter)
Debug.Print ActiveFile
If Right(ActiveFile, 3) = YourFileType Then
Set NewWb = Application.Workbooks.Open(YourDirectory & ActiveFile)
Call YourMacro(NewWb)
NewWb.SaveAs YourDirectory & Left(ActiveFile, Len(ActiveFile) - 4) & ".xlsx"
NewWb.Saved = True
NewWb.Close
Set NewWb = Nothing
End If
Next FileCounter
End If
End Sub
You missing the functions GetFileList and YourMacro. A quick search brought me to this website (I think you copied it from there). http://www.ozgrid.com/forum/printthread.php?t=56393
There are the missing functions. Copy those two also in your modul to make it run (I tested it with pdf-Files):
Function GetFileList(FileSpec As String) As Variant
' Author : Carl Mackinder (From JWalk)
' Last Update : 25/05/06
' Returns an array of filenames that match FileSpec
' If no matching files are found, it returns False
Dim FileArray() As Variant
Dim FileCount As Integer
Dim FileName As String
On Error GoTo NoFilesFound
FileCount = 0
FileName = Dir(FileSpec)
If FileName = "" Then GoTo NoFilesFound
' Loop until no more matching files are found
Do While FileName <> ""
FileCount = FileCount + 1
ReDim Preserve FileArray(1 To FileCount)
FileArray(FileCount) = FileName
FileName = Dir()
Loop
GetFileList = FileArray
Exit Function
NoFilesFound:
GetFileList = False
End Function
Sub YourMacro(Wb As Workbook)
Dim ws As Worksheet
Set ws = Wb.Worksheets(1)
ws.Range("A6").Value = "=((+A2*$CN2)+(A3*$CN3)+(A4*$CN4)+(A5*$CN5))/SUM($CN2:$CN5)"
ws.Range("A6").Copy ws.Range("B6:CM6")
ws.Range("CO6").Value = "=CO2"
End Sub
To save files in a different directory:
Dim SaveDirectory As String
SaveDirectory = "c:\Users\navin\Desktop\test\converted to excel"
Replace this line
NewWb.SaveAs YourDirectory & Left(ActiveFile, Len(ActiveFile) - 4) & ".xlsx"
with this
NewWb.SaveAs SaveDirectory & Left(ActiveFile, Len(ActiveFile) - 4) & ".xlsx"

Excel VBA: select one row down in a loop

I have a source folder that contains many xls files. I want to create a master file - collect all information into one database from all files in the given source.
The following code creates 2 columns in master file and enters 2 values from the given source file (one file):
Sub getData()
Dim XL As Excel.Application
Dim WBK As Excel.Workbook
Dim scrFile As String
Dim myPath As String
myPath = ThisWorkbook.path & "\db\" 'The source folder
scrFile = myPath & "1.xlsx" 'Select first file
' Sheet name in the master file is "Sh"
ThisWorkbook.Sheets("Sh").Range("A1").Value = "Column 1"
ThisWorkbook.Sheets("Sh").Range("B1").Value = "Column 2"
Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open(scrFile)
ThisWorkbook.Sheets("Sh").Range("A2").Value = WBK.ActiveSheet.Range("A10").Value
ThisWorkbook.Sheets("Sh").Range("B2").Value = WBK.ActiveSheet.Range("C5").Value
WBK.Close False
Set XL = Nothing
Application.ScreenUpdating = True
End Sub
Now I want to loop through all files and save the values from cells "A10" and "C5" from each file in one database, so the loop should select the next row to save new values.
I have an idea how to loop through all files, but don't know how to switch to the next row:
scrFile = Dir(myPath & "*.xlsx")
Do While scrFile <> ""
Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open(scrFile)
' Here should be the code to save the values of A10 and C5 of the given file
'in the loop in next available row of the master file.
WBK.Close False
Set XL = Nothing
scrFile = Dir
Loop
Any help will be highly appreciated! :)
For simplicity, just use a counter:
scrFile = Dir(myPath & "*.xlsx")
n = 1 ' skip the first row with headers
Do While scrFile <> ""
n = n + 1
Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open(scrFile)
' save the values of A10 and C5 of the given file in the next row
ThisWorkbook.Sheets("Sh").Range("A" & n).Value = WBK.ActiveSheet.Range("A10").Value
ThisWorkbook.Sheets("Sh").Range("B" & n).Value = WBK.ActiveSheet.Range("C5").Value
WBK.Close False
Set XL = Nothing
scrFile = Dir
Loop
msgbox n & " files imported."
BTW, you don't need to start a second Excel instance (CreateObject("Excel.Application")) just to open a second workbook. This will slow down your code a lot. Just open, read and close it. Address your master workbook not by ThisWorkbook but assign a varible to it:
Dim masterWB As Excel.Workbook
set masterWB = ThisWorkbook
...
masterWB.Sheets("Sh").Range("A" & n).Value = WBK.ActiveSheet.Range("A10").Value
You need to recalculate last row in the loop wtih End() function.
Like this for range .Range("A" & .Rows.Count).End(xlUp).Offset(1, 0)
Or to have an integer .Range("A" & .Rows.Count).End(xlUp).Offset(1, 0).Row
Give this a try :
Sub getData()
Application.ScreenUpdating = False
Dim XL As Excel.Application, _
WBK As Excel.Workbook, _
MS As Worksheet, _
scrFile As String, _
myPath As String
'Sheet name in the master file is "Sh"
Set MS = ThisWorkbook.Sheets("Sh")
'The source folder
myPath = ThisWorkbook.Path & "\db\"
MS.Range("A1").Value = "Column 1"
MS.Range("B1").Value = "Column 2"
Set XL = CreateObject("Excel.Application")
scrFile = Dir(myPath & "*.xlsx")
Do While scrFile <> ""
Set WBK = XL.Workbooks.Open(scrFile)
' Here should be the code to save the values of A10 and C5 of the given file
'in the loop in next available row of the master file.
With MS
.Range("A" & .Rows.Count).End(xlUp).Offset(1, 0).Value = WBK.ActiveSheet.Range("A10").Value
.Range("B" & .Rows.Count).End(xlUp).Offset(1, 0).Value = WBK.ActiveSheet.Range("C5").Value
End With
WBK.Close False
scrFile = Dir
Loop
XL.Quit
Set XL = Nothing
Set MS = Nothing
Set WBK = Nothing
Application.ScreenUpdating = True
End Sub
I actually have a code here that will loop through each file and deposit the code into your main file. You are also able to choose the directory of the target folder.
Sub GatherData()
Dim sFolder As String
Application.ScreenUpdating = True
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "Please select a folder..."
.Show
If .SelectedItems.Count > 0 Then
sFolder = .SelectedItems(1) & "\"
Else
Exit Sub
End If
End With
Call Consolidate(sFolder, ThisWorkbook)
End Sub
Private Sub Consolidate(sFolder As String, wbMaster As Workbook)
Dim wbTarget As Workbook
Dim objFso As Object
Dim objFiles As Object
Dim objSubFolder As Object
Dim objSubFolders As Object
Dim objFile As Object
Dim ary(3) As Variant
Dim lRow As Long
'Set Error Handling
On Error GoTo EarlyExit
'Create objects to enumerate files and folders
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFiles = objFso.GetFolder(strFolder).Files
Set objSubFolders = objFso.GetFolder(strFolder).subFolders
'Loop through each file in the folder
For Each objFile In objFiles
If InStr(1, objFile.Path, ".xls") > 0 Then
Set wbTarget = Workbooks.Open(objFile.Path)
With wbTarget.Worksheets(1)
ary(0) = .Range("B8") 'here you can change the cells you need the data from
ary(1) = .Range("B12")
ary(2) = .Range("B14")
End With
With wbMaster.Worksheets(1)
lRow = .Range("E" & .Rows.Count).End(xlUp).Offset(1, 0).Row 'here you can change the row the data is deposited in
.Range("E" & lRow & ":G" & lRow) = ary
End With
wbTarget.Close savechanges:=False
End If
Next objFile
'Request count of files in subfolders
For Each objSubFolder In objSubFolders
Consolidate objSubFolder.Path, wbMaster
Next objSubFolder
EarlyExit:
'Clean up
On Error Resume Next
Set objFile = Nothing
Set objFiles = Nothing
Set objFso = Nothing
On Error GoTo 0
End Sub

how to load a sectioned CSV file to an excel sheet?

CSV file:
#3GMACRO,,,,,,,,,,,,,,
,,,,,,,,,,,,,,
IMSI,IMEI,Date,Time,UMTS MACRO-UARFCNDL,UMTS MACRO-PrimaryScramblingCode,UMTS MACRO-CPICHTxPower,UMTS MACRO-PLMNCellId,UMTS MACRO- RNCId,UMTS MACRO-MCC,UMTS MACRO-MNC,UMTS MACRO - LAC,UMTS MACRO - RAC,UMTS MACRO - MaxUETxPower,UMTS MACRO - MeasuredRSCP
2.6275E+14,3.57539E+14,20100107,160000,10662,11,-99,268435456,0,0,0,1,0,0,-74
,,,,,,,,,,,,,,
#3GFEMTO,,,,,,,,,,,,,,
,,,,,,,,,,,,,,
IMSI,IMEI,Date,Time,UMTS FEMTOS-UARFCNDL,UMTS FEMTOS-PrimaryScramblingCode,UMTS FEMTOS-CPICHTxPower,UMTS FEMTOS-PLMNCellId,UMTS FEMTOS-RNCId,UMTS FEMTOS-MCC,UMTS FEMTOS-MNC,UMTS FEMTOS-LAC,UMTS FEMTOS-RAC,UMTS FEMTOS-MaxUETxPower,UMTS FEMTOS- MeasuredRSCP
2.6275E+14,3.57539E+14,20100107,160000,10687,252,-24,61,0,610,3956,486,11,5,-102
,,,,,,,,,,,,,,
#2GMACRO,,,,,,,,,,,,,,
,,,,,,,,,,,,,,
IMSI,IMEI,Date,Time,GSM MACRO_CellID,GSM MACRO-MCC,GSM MACRO-MNC,GSM MACRO-LAC,GSM MACRO-RAC,GSM MACRO-Max permitted UE Tx power (SIB3),GSM MACRO-Measure RSSI,,,,
2.6275E+14,3.57539E+14,20100107,160000,GSM_Cell_Id=1,2,3,4,5,6,7,,,,
i want this csv file to be loaded into an excel sheet as an individual section when I click load only once (ie each section should go to separate worksheet in excel)
CSV file contain Section name , header and data
Below are the section names in CSv file
3GMACRO
3GFEMTO
2GMACRO
Below are the Header names in CSv file
IMSI,IMEI,Date,Time,GSM MACRO_CellID,GSM MACRO-MCC,GSM MACRO-MNC............ etc
3 worksheets should have headers and data after loading CSV file.
Please help me in doing so.
Thanks in advance
hi
this is what the code i tried but its not working perfectly as needed.
Sub loadData()
'Runtime error handling
'On Error Resume Next
'Unprotect the password protected sheet for loading csv data
ActiveSheet.Unprotect Password:=pass
'Variable declaration
Dim strFilePath As String, strFilename As String, strFullPath As String
Dim lngCounter As Long
Dim oConn As Object, oRS As Object, oFSObj As Object
'Get a text file name
strFullPath = Application.GetOpenFilename("Text Files (*.csv),*.csv", , "Please select text file...")
'MsgBox "stringfullpath" & strFullPath
If strFullPath = "False" Then Exit Sub 'User pressed Cancel on the open file dialog
'This gives us a full path name e.g. C:tempfolderfile.txt
'We need to split this into path and file name
Set oFSObj = CreateObject("SCRIPTING.FILESYSTEMOBJECT")
strFilePath = oFSObj.GetFile(strFullPath).ParentFolder.Path
strFilename = oFSObj.GetFile(strFullPath).Name
'Open an ADO connection to the folder specified
Set oConn = CreateObject("ADODB.CONNECTION")
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strFilePath & ";" & _
"Extended Properties=""text;HDR=Yes;FMT=Delimited"""
Set oRS = CreateObject("ADODB.RECORDSET")
'Now actually open the text file and import into Excel
'oRS.Open "SELECT * FROM " & strFilename & " , oConn"
oRS.Open "SELECT * FROM " & strFilename, oConn
While Not oRS.EOF
Sheets("Neighbour3GMacro").Range("A3").CopyFromRecordset oRS
'Sheets.Add Type:=Application.GetOpenFilename & " *.csv"
Sheets("Neighbour3GFemto").Range("A2").CopyFromRecordset oRS
Sheets("Neighbour2GMacro").Range("A2").CopyFromRecordset oRS
Wend
oRS.Close
oConn.Close
End Sub
You can use the Split function to get an array and use this array to fill a Row. Here is a simple solution.
You will need to change Sheet1, Sheet2, Sheet3 to your worksheet-names and might want to add functionality to ignore header lines. If you have a fix ColumnCount you can also replace the Ubound function with an integer variable.
Sub loadData2()
Dim strFullPath As String
Dim oFSOBj As Object 'Scripting.FileSystemObject'
Dim oFileStream As Object 'Scripting.TextStream'
Dim targetSheet As Worksheet
Dim iRow As Long
Dim startRow As Long
Dim startColumn As Integer
Dim line As String
'Please insert Error Handling etc.'
'Get a text file name '
strFullPath = Application.GetOpenFilename("Text Files (*.csv),*.csv", , "Please select text file...")
If strFullPath = "False" Then Exit Sub 'User pressed Cancel on the open file dialog'
Set oFSOBj = CreateObject("SCRIPTING.FILESYSTEMOBJECT")
Set oFileStream = oFSOBj.GetFile(strFullPath).OpenAsTextStream(ForReading)
Set targetSheet = Sheet1
iRow = 0
startRow = 3
startColumn = 1
While (Not oFileStream.AtEndOfStream)
line = oFileStream.ReadLine
If (Left(line, 1) = "#") Then
iRow = 0
If (Left(line, 8) = "#3GMACRO") Then Set targetSheet = Sheet1
If (Left(line, 8) = "#3GFEMTO") Then Set targetSheet = Sheet2
If (Left(line, 8) = "#2GMACRO") Then Set targetSheet = Sheet3
ElseIf Trim(line) <> vbNullString Then 'Else Block: line has content'
csline = Split(line, ",")
targetSheet.Range(targetSheet.Cells(startRow + iRow, startColumn), targetSheet.Cells(startRow + iRow, startColumn + UBound(csline))).Value2 = csline
iRow = iRow + 1
End If
Wend
oFileStream.Close
Set oFileStream = Nothing
Set oFSOBj = Nothing
End Sub