Excel file import, Comma as delimiter - excel

Hi have been working on a method to import a text file into a specified worksheet, within a master workbook. Up until recently the file used Tab as the delimiter, which I was able to specify like so:
workbooks.open fileToOpen,,,,,,,,vbtab
now the file has switched to the use of a comma, which i have tried to specify in the line above but have been unable to get to work. im fairly new at this so not sure what my options. is there a way that I can get the code to identify the delimiter and convert based on that?
any help appreciated
copy of code :
Sub Multi_T_Import()
Dim fileToOpen, closeWorkbook, searchchar, sName As String
Dim chkFile, fileImport As Integer
Dim FinalRow As Long
Dim LastCol As Long
searchchar = "\"
'Turn off any prompts
MsgBox "Please Select Multi Token Data File" & vbNewLine & "MULTI TOKEN DATA IMPORT"
'Select the file to import
fileToOpen = Application _
.GetOpenFilename("txt Files (*.txt), *.txt")
'Option to import a different fileIf fileToOpen <> False Then
If fileToOpen <> False Then
fileImport = MsgBox("Are you sure you want to import " & fileToOpen, vbYesNo)
If fileImport = vbNo Then
MsgBox "Import of " & fileToOpen & " has been aborted"
Exit Sub
End If
End If
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.CutCopyMode = False
If fileImport = False Then Exit Sub
Workbooks.Open fileToOpen
Sheets.Select
If ActiveSheet.AutoFilterMode = True Then ActiveSheet.AutoFilterMode = False
FinalRow = Range("A" & Rows.Count).End(xlUp).Row
FinalRow = FinalRow + 1
Range("A1:V" & FinalRow).Select
Selection.Copy
Windows(MasterFileName).Activate
Sheets("Multi_Token_Report").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'Columns("Q").Cut
'Columns("A").Insert
closeWorkbook = Mid(fileToOpen, InStrRev(fileToOpen, searchchar) + 1)
Workbooks(closeWorkbook).Close SaveChanges:=False
Dim oFS As Object
Set oFS = CreateObject("Scripting.FileSystemObject")
Range("X1").Select
ActiveCell.FormulaR1C1 = oFS.GetFile(fileToOpen).DateLastModified
Set oFS = Nothing
End Sub

There is a build-in function for separating things like comma, tab or else.
After you load in txt, it use the first column to store data. So, simply select all data on A column and use the build in function.
in VBA code, it is something like this, [ after opening txt in excel ]
Workbooks(NewWB).Sheets(1).Range("A1").EntireColumn.TextToColumns Destination:=Range("A1"), Comma:=True
enter image description here

Related

Specifying file name when saving using VBA in excel returning a blank

I am trying to get this code to work but when the save dialogue opens the suggested file name is blank. I traced the variable "saveFile" in the locals window and it's false instead of the string value. I'm not sure why.
Simply, I want the file name to be the suppliername followed by the word batch add and then today's date.
Thanks is advance
Sub SaveToExcelFile()
On Error GoTo 1
Dim wb As Workbook
Dim filesavename As String
Dim saveFile As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Range("G3").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
MsgBox ("Êã ÍÐÝ ßæÏ ÇáæÒä")
Range("H3").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
MsgBox ("Êã ÍÐÝ ßæÏ ÇáÍÌã")
filesavename = Range("SupplierName")
Range("A2").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Set WorkRng = Application.Selection
def = Application.SheetsInNewWorkbook
Application.SheetsInNewWorkbook = 1
Set wb = Application.Workbooks.Add
Application.SheetsInNewWorkbook = def
WorkRng.Copy
wb.Worksheets(1).Paste
daytouse = Day(Date)
monthtouse = Month(Date)
yeartouse = Year(Date)
Dim dateasstring As String
dateasstring = daytouse & "." & monthtouse & "." & yeartouse
Dim XPath As String
XPath = "C:\Users\mahmoud.senosy\Desktop\BatchAdd\"
filesavename = XPath & filesavename & " Batch Add " & dateasstring
saveFile = Application.GetSaveAsFilename(filesavename, fileFilter:="Excel Workbooks (*.xlsx),*.xlsx")
wb.SaveAs Filename:=saveFile
wb.Close
Application.CutCopyMode = False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Done: Exit Sub
1: MsgBox "ÇáÍÝÙ ÝÔá :)"
End Sub
-delete the "saveFile = " from:
saveFile = Application.GetSaveAsFilename(filesavename, fileFilter:="Excel Workbooks (.xlsx),.xlsx")
instead try:
Application.GetSaveAsFilename(filesavename, fileFilter:="Excel Workbooks (.xlsx),.xlsx")

My code is not deleting rows, rest all is working fine

I have complied the below code for creating a separate bank payment sheet, everything is working fine but it is not deleting the rows of the cells whose value is "Delete" in column "E".
i have also observed while debugging that sometimes it deletes and sometimes it don't.
but now it is not deleting at all.
where I'm going wrong?
Sub Create_Bank_Sheet()
Dim fname As String
Dim path As String
Dim varResponse As Variant
Application.DisplayAlerts = False
varResponse = MsgBox("Select 'Yes' or 'No' File will be Saved at : " & Range("c43").Value, vbYesNo, "Are you sure you want to SaveAs this Sheet?")
If varResponse <> vbYes Then Exit Sub
Sheets("Bank Sheet for Payment").Select
path = Sheets("Command Center").Range("c43")
fname = Sheets("Command Center").Range("c42")
ThisWorkbook.Sheets("Bank Sheet for Payment").Copy
Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Dim c As Range
Dim SrchRng As Range
Dim SrchStr As String
Set SrchRng = ActiveSheet.Range("e4", ActiveSheet.Range("e65536").End(xlUp))
SrchStr = "Delete"
Do
Set c = SrchRng.Find(SrchStr, LookIn:=xlValues)
If Not c Is Nothing Then c.EntireRow.Delete
Loop While Not c Is Nothing
ActiveWorkbook.Save
MsgBox ("File saved in " & path)
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
You're not setting your SrchRng correctly.
Try
Set SrchRng = ActiveSheet.Range("E4:E" & ActiveSheet.Range("E65536").End(xlUp).Row)

How to Insert workbook name in all worksheets in first column of all rows (used rows) in a folder

I have a task to add workbook name into all worksheet's first column hence i need to have a macro and below is a draft of the same
Sub InsertWorkbookName()
Path = "C:\Users\mechee69\Download\"
Filename = Dir(Path & "*.xls")
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Columns("A:A").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("A1").Select
ActiveCell.SpecialCells(xlLastCell).Select
Application.Goto Range("A" & ActiveCell.Row), True
ActiveCell.Select
ActiveCell.FormulaR1C1 = _
"=RIGHT(LEFT(CELL(""filename""),FIND(""."",CELL(""filename""),FIND(""["",CELL(""filename""),1))-1),FIND(""."",CELL(""filename""),FIND(""["",CELL(""filename""),1))-FIND(""["",CELL(""filename""),1)-1)"
Application.Goto Range("A" & ActiveCell.Row), True
ActiveCell.Select
Selection.Copy
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
ActiveWorkbook.Save
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub
Try this
Sub WorkbookName()
Dim wbk As Workbook
Dim strFilename As String
Dim strPath As String
Dim wc As Worksheet
Dim lngLastR As Long
Dim lngSecurity as Long
lngSecurity = Application.AutomationSecurity
Application.AutomationSecurity = msoAutomationSecurityLow
strPath = "[Full Folder Path]"
strFilename = Dir(strPath & "*.xlsx")
Do While strFilename <> ""
Set wbk = Workbooks.Open(strPath & strFilename)
For Each ws In wbk.Worksheets
lngLastR = ws.Range("A" & Rows.Count).End(xlUp).Row
ws.Range("A:A").Insert Shift:=xlToRight
ws.Range("A1:A" & lngLastR).Value = wbk.Name
Next
wbk.Save
wbk.Close False
strFilename = Dir
Loop
Application.AutomationSecurity = lSecurity
MsgBox ("Done")
End Sub
As a quick run through of what this code does.
'Dir' goes through a folder on a criteria, the criteria in this case being ".xlsx" this is to make sure it only opens xlsx files.
'Do While' is a form of loop, this will repeat all code between the "Do While" and the "Loop" until the condition is no longer true.
Once deciding on the file it opens the workbook and remembers it as a variable, this is so I can reference it's name more easily.
I then find the last used row by starting at the bottom cell of row "A" and going up until there is data in a cell. There is a write up on this on stack overflow (Link: Error in finding last used cell in VBA)
I then insert a row to the left pushing the data to the right and set the value of all cells in row 'A' in the used ranged to the name of the workbook using the workbooks '.Name' function.
I then save and close the workbook before using the 'Dir' to the next file name ready to start the process again, this will repeat for all files and give you a message box saying "Done" once it has completed them all.
If you have any questions let me know
Edited to include a bypass for protected view
So this Macro will open Excel Files in a Folder with a specific format, then it prints the workbookname in A1 in every sheet of that file. It ignores the master, if its in the same folder.
Sub WorkbookName()
Dim wbk As Workbook
Dim Filename As String
Dim Path As String
Dim lastRow As Long
Dim lSecurity As Long
On Error Resume Next
Path = "C:\Users\User\Desktop\Files\" 'Folder of your Files
Filename = Dir(Path & "*.xlsx") 'Format of your files
Do While Filename <> "" And Filename <> "Master.xlsm" 'Dont Open MasterFile
Set wbk = Workbooks.Open(Path & Filename)
lSecurity = Application.AutomationSecurity
Application.AutomationSecurity = msoAutomationSecurityLow
For Each ws In wbk.Worksheets
With ws
.Range("A1").EntireColumn.Insert
lastRow = .Cells(Rows.Count, 2).End(xlUp).Row
.Range(Cells(1, 1), Cells(lastRow, 1)).Value = ActiveWorkbook.Name
End With
Application.AutomationSecurity = lSecurity
Next ws
wbk.Close True
Filename = Dir
Loop
End Sub

copy specific excel sheets to a new workbook as values

Current code:
Private Sub cmdsave_Click()
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("payin")
'find first empty row in database
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
'copy the data to the database
With ws
.Cells(iRow, 1).Value = Me.txtlbp.Value
.Cells(iRow, 2).Value = Me.txtdollar.Value
.Cells(iRow, 3).Value = Me.txtsyp.Value
End With
'clear the data
Me.txtlbp.Value = ""
Me.txtdollar.Value = ""
Me.txtsyp.Value = ""
ActiveWorkbook.Save
Dim savedate
savedate = Date
Dim savetime
savetime = Time
Dim formattime As String
formattime = Format(savetime, "hh.MM.ss")
Dim formatdate As String
formatdate = Format(savedate, "DD-MM-YYYY")
Application.DisplayAlerts = False
If Len(Dir("D:\cashbackup\english", vbDirectory)) = 0 Then
MkDir "D:\cashbackup\english"
End If
Dim backupfolder As String
backupfolder = "D:\cashbackup\english\"
ActiveWorkbook.SaveCopyAs Filename:=backupfolder & "payin" & formatdate & " " & formattime & " " & ActiveWorkbook.Name
Application.DisplayAlerts = False
txtlbp.SetFocus
End Sub
the current code is saving a copy of the whole file to the directory "D:\cashbackup\english", which is taking a lot of space on disk (about 3.73 MB for each save click), where as saving only sheets: payin, payout and balance as values only without the formulas created previously in excel cells in the excel project file will save much space on the hard disk (not more than 20 KB for each save click)
my need:
I want the code save a new workbook containing only specific sheets: payin, payout and balance as values in the directory: "D:\cashbackup\english", with the same file naming, I mean without the user forms in sheet BOX and without the macros
Thank you in advance.
New Version, but remember: The site it's not a place to find people that make your work, but a place to find an help for writed code... Or a starting point. The macro use the open file and make:
delete the sheets not included in the "list"
remove the formulas
put all the cells in protected mode
add password to all the sheets
save with password (for Open & Modify)
remove the macro from the files (saving in Xlsx)
Code:
Application.DisplayAlerts = False
For Each xx In ActiveWorkbook.Sheets
If xx.Name = "Sheet1" Or xx.Name = "Sheet3" Then
xx.Select
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.Locked = True
ActiveSheet.Protect Password:="ShPwd", DrawingObjects:=True, Contents:=True, Scenarios:=True
Else
xx.Delete
End If
Next
tmp = " - " & Format(Date, "DD-MM-YYYY") & " - " & Format(Time, "HH-MM-SS")
ActiveWorkbook.Protect Password:="ShPwd", Structure:=True, Windows:=False
ActiveWorkbook.SaveAs Filename:="E:\0\New folder\aa" & tmp & ".xlsx", FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False, Password:="Open" _
, WriteResPassword:="Modify"
ActiveWindow.Close
Application.DisplayAlerts = True

Copy and paste a row into column using macro

I am very new to the macro..
Basically I wanted to copy a row (E23 to H23) from worksheet named "Present month" of one workbook to a column of another worksheet named "ANA" (K4 to K7) in another workbook.
Please help me out!!
Edit1: Code from comment
Sub Copy_and_update_last_col_Census()
Range("K4:K7").Select
Selection.ClearContents
Application.WindowState = xlNormal
'the below line throws error
Windows("NOL_Support_Ticket_Status_Report").Activate
Range("E25:H25").Select
Selection.copy
Windows("Charts.xlsm").Activate
Range("K9").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.copy
Range("K4").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Application.CutCopyMode = False
Range("K9:N9").Select
Selection.ClearContents
End Sub
This is a tip. Go to the Developers tab -> Record Macro -> do the actions you want -> stop recording and woila press alt + F11 and check out the module.
F8 is your friend and you can see what your recorded macro does!!!
try this:
Sub Copy_and_update_last_col_Census()
Dim wb As Workbook
Dim rng2copy As Range, rng2paste As Range
Dim query As Integer
Dim myfile
Dim filename As String
'~~> I assumed that Charts.xlsm is the workbook you are running the macro
Set rng2paste = ThisWorkbook.Sheets("ANA").Range("K4")
filename = "NOL_Support_Ticket_Status_Report.xlsx"
'~~> Handles the error if workbook is not open
On Error Resume Next
Set wb = Workbooks(filename)
'~~> check for error and execute action necessary
If Err.Number <> 0 Then
query = MsgBox("Source workbook not open." & vbNewLine & _
"Do you want to open it?", vbYesNo)
Else
GoTo proceedcopy
End If
If query = 6 Then
myfile = Application.GetOpenFilename(Filefilter:="Excel Files (*.xlsx), *.xlsx")
Else
MsgBox "Exiting now."
Exit Sub
End If
'~~> check if user selected the correct file
If myfile <> False Then
If Dir(myfile) = filename Then
Set wb = Workbooks.Open(myfile)
Else
MsgBox "Wrong file loaded." & vbNewLine & _
"Exiting now."
Exit Sub
End If
Else
MsgBox "No file loaded." & vbNewLine & _
"Exiting now."
Exit Sub
End If
'~~> this do the actual copying
proceedcopy:
Set rng2copy = wb.Sheets("Present Month").Range("E23", "H23")
rng2copy.Copy
rng2paste.PasteSpecial xlPasteValues, , , True
Application.CutCopyMode = False
wb.Close False
End Sub
This is tried and tested.
But i can't say that i've structured it well enough.
So i leave further testing to you.

Resources