open a csv file in an active worksheet vba on mac - macos

I am trying to rewrite my windows VBA code so i can use it on a Mac computer.
But somehow it is not possible to load the information into an active worksheet on mac.
Where MyFiles is the csv file opened by the code of http://www.rondebruin.nl/mac/mac015.html
.
I broke down the code a bit because i thought it didn't recognize the workbook. But i think the problem lies in the work book.
Set ws = ActiveWorkbook.Sheets("1. Pledges (ruw)")
MyFiles = MacScript(MyScript)
On Error GoTo 0
If MyFiles <> "" Then
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
With ws.QueryTables.Add(Connection:="TEXT;" & MyScript, Destination:=ws.Range("A1"))
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.Refresh
End With
If ws.Range("A2").Value = vbNullString Then
ws.rows("2").EntireRow.Delete
End If
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End If
End Sub
Some how it always crashes on the .refresh even if i use the code of robin the bruijn i can't use the querytables which work perfectly on windows.
Original windows code:
Dim ws As Worksheet, strFile As String
Set ws = ActiveWorkbook.Sheets("1. Pledges (ruw)") 'set to current worksheet name
strFile = Application.GetOpenFilename("Text Files (*.csv),*.csv", , "Please selec text file...")
With ws.QueryTables.Add(Connection:="TEXT;" & strFile, Destination:=ws.Range("A1"))
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.SaveData = True
End With
If ws.Range("A2").Value = vbNullString Then
ws.rows("2").EntireRow.Delete
End If

Related

Microsoft VS - Access

I'm having a problem with access-VS it's ways Variable not defined can anyone help me?
This is the code that i'm working on: (am a newbie)
Option Compare Database
Option Explicit
Private Sub btnLogin_Click()
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("tbl1Employees", dbOpenSnapshot, dbReadOnly)
rs.FindFirst "UserName='" & Me.txtUserNAme & "'"
If rs.NoMatch = True Then
Me.lblWrongUser.Visible = True
Me.txtUserNAme.SetFocus
Exit Sub
End If
Me.lblWrongUser.Visible = False
If rs!Password <> Nz(Me.txtPassword, "") Then
Me.lblWrongPass.Visible = True
Me.txtPassword.SetFocus
Exit Sub
End If
Me.lblWrongPass.Visible = False
DoCmd.OpenForm "frmMenu"
DoCmd.Close acForm, Me.Name
End Sub

Compile error: Can't find project or library (OSX)

I've run into a bit of a problem with making my macros compatible with OSX where it works on windows.
I have the following issue:
Compile error: Can't find project or library error when running the macro on Office 2016 on a MAC
The code/ function is used to change specific ranges to Upper Case / Proper case. The debugger highlights "UCase(Cell)" and "Cell"
Sub ChkSheet()
'=========================================================================
' Format the cell boarders when the info needs to be corrected or updated
'=========================================================================
Dim historyWks As Worksheet
Set historyWks = Worksheets("Namelist")
Dim lRow As Long
Dim emailRng As Range
Dim Cell As Range
With historyWks
' Flags cells where the Email fieldcontains invalid characters
lRow = Range("G" & Rows.Count).End(xlUp).Row
Set emailRng = Range("Q2:Q" & lRow)
For Each Cell In emailRng
If Cell.Value = "," _
Or Cell.Value = " " _
Or Cell.Value = "wd" _
Or Cell.Value = "" _
Or Cell.Find("#") Is Nothing Then
Cell.Interior.Color = vbRed
Else:
Cell.Interior.ColorIndex = 0
End If
Next
'Change the text case
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
For Each Cell In Range("NListUpper")
Select Case True
Case Application.IsText(Cell) = True
Cell = UCase(Cell)
End Select
Next Cell
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
'Change the case to proper
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
For Each Cell In Range("NListProp")
Select Case True
Case Application.IsText(Cell) = True
Cell = StrConv(Cell, vbProperCase)
End Select
Next Cell
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End With
End Sub
I've noticed that some libraries are missing on Excel 2016 on OSX and i'm aware that MS has dropped many libraries out of Excel for OSX.
Any advice on this would be just great.
Can you try avoiding using default properties of the Range object - they might differ between Windows and OSX:
So, instead of:
Select Case True
Case Application.IsText(Cell) = True
Cell = UCase(Cell)
End Select
Can you just try:
If Application.IsText(Cell.Value) Then
Cell.Value = UCase(Cell.Value)
End If

Multiple CSVs to single excel VBS

I am trying to read multiple CSVs into single spreadsheet. I got below code from google.
There are 10 CSVs present in "C:\Users\achayapa\Desktop\test". I need to have each of these CSVs in a single excel. could someone please help?
I am new to vb script.
Sub MacroLoop()
Dim strFile As String
Dim ws As Worksheet
strFile = Dir("C:\Users\achayapa\Desktop\test\*.csv")
Do While strFile <> vbNullString
ws = Sheets.Add
With ws.QueryTables.Add(Connection:= _
"TEXT;" & "C:\Users\achayapa\Desktop\test\" & strFile, Destination:=Range("$A$1"))
.Name = strFile
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh(BackgroundQuery:=False)
End With
strFile = Dir
Loop
End Sub
I just thought of sharing the answer to above question.
Create a VBA script as below:
Sub Macro1()
Dim strPath As String
Dim strFile As String
strPath = "C:\test\"
strFile = Dir(strPath & "*.csv")
Do While strFile <> ""
With ActiveWorkbook.Worksheets.Add
With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
Destination:=.Range("A1"))
.Parent.Name = Replace(strFile, ".csv", "")
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End With
strFile = Dir
Loop
End Sub
In above code include for path - '\' For example - C:\test\
After this follow include above VBA in Excel, follow steps as in below link:
http://www.ablebits.com/office-addins-blog/2013/12/06/add-run-vba-macro-excel/
Short answer: Yes it is possible.
Step 0 of long answer:
There are 2 syntactical errors in you SWub MacroLoop():
ws = Sheets.Add must be Set ws = Sheets.Add because you want to assign an object to ws.
.Refresh(BackgroundQuery:=False) must be .Refresh BackgroundQuery:=False because you must not use param list () when calling (a function/method as) a Sub (see here).
You may get problems with .TextFilePlatform and .TextFileTrailingMinusNumbers - at least I did when testing on my rather dated Excel. If so, disable those lines (' comment) and try again.
For the next step I would need a detailed account of your testing experience. What result do you expect and how did the actual outcome differ from that?

How do you rename a file URL to a variable in VB script?

I'm making a program in Microsoft Excel using a bunch of VB script macros.
One of my macros gets data "From Web" and retrieves the table to a sheet in excel. When I say "From Web", I just copied and pasted the URL from an html file I have on my desktop. The location of my program is going to change frequently, so I need to be able to have a cell in excel where I can specify this URL, which my macro will reference.
Here is my code below:
Sub ImportSwipeDataWithTitlesBeta()
'
' ImportSwipeDataWithTitlesBeta Macro
'
' Keyboard Shortcut: Ctrl+Shift+K
'
Sheets("Import Swipe Data").Select
Cells.Select
Selection.Delete Shift:=xlUp
Range("A3").Select
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;file:///C:/Users/Sean/Desktop/Attendance Program ADC/ACS%20OnSite%20SE%20Complete.htm", _
Destination:=Range("$A$3:$C$3"))
.Name = "ACS%20OnSite%20SE%20Complete_8"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
Sheets("Resource Sheet").Select
Range("B2:C2").Select
Selection.Copy
Sheets("Import Swipe Data").Select
Range("A1:B1").Select
ActiveSheet.Paste
Range("A2").Select
End Sub
Thanks for the Help!
You don't need to .Select every range you use. These statements are generated by recording a macro but you can clean your code afterwards as described here.
Yet, to answer your question, you can store your URL in a var:
Dim myURL As String
myURL = "URL;" & Sheets("Import Swipe Data").Range("A1").Value
With ActiveSheet.QueryTables.Add(Connection:= myURL, Destination:=Range("$A$3:$C$3"))
(...)
End With
Regards,

Upgrading VB6 code from Outlook 2007 to Outlook 2010

We want to upgrade our VB6 code to use Outlook 2010, but we're getting the following error:
Active x cannot create object
This is our current code:
Public Sub SendEmail()
Set emailOutlookApp = CreateObject("Outlook.Application.12")
Set emailNameSpace = emailOutlookApp.GetNamespace("MAPI")
Set emailFolder = emailNameSpace.GetDefaultFolder(olFolderInbox)
Set emailItem = emailOutlookApp.CreateItem(olMailItem)
Set EmailRecipient = emailItem.Recipients
EmailRecipient.Add (EmailAddress)
EmailRecipient.Add (EmailAddress2)
emailItem.Importance = olImportanceHigh
emailItem.Subject = "My Subject"
emailItem.Body = "The Body"
'-----Send the Email-----'
emailItem.Save
emailItem.Send
'-----Clear out the memory space held by variables-----'
Set emailNameSpace = Nothing
Set emailFolder = Nothing
Set emailItem = Nothing
Set emailOutlookApp = Nothing
Exit Sub
I'm not sure if "Outlook.Application.12" is correct. But I can't find a definitive answer for this.
For Outlook 2010, this is definitly corect Outlook.Application.14.
But, I don't know what about office 2007.
I think it's Outlook.Application.12 and for lower versions it is simply "Outlook.Application".
Here's the code I switched to for 2010:
Private Sub EmailBlahbutton_Click()
Dim mOutlookApp As Object
Dim OutMail As Object
Dim Intro As String
On Error GoTo ErrorHandler
Set mOutlookApp = GetObject("", "Outlook.application")
Set OutMail = mOutlookApp.CreateItem(0)
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
'These are the ranges being emailed.
ActiveSheet.Range(blahblahblah).Select
'Intro is the first line of the email
Intro = "BLAHBLAHBLHA"
'Set the To and Subject lines. Send the message.
With OutMail
.To = "blahblah#blah.com"
.Subject = "More BLAH here"
.HTMLBody = Intro & RangetoHTML(Selection)
.Send
End With
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
ActiveSheet.Range("A1").Select
ActiveWindow.ScrollColumn = ActiveCell.Column
ActiveWindow.ScrollRow = ActiveCell.Row
Set OutMail = Nothing
Set mOutlookApp = Nothing
Exit Sub
ErrorHandler:
Set mOutlookApp = CreateObject("Outlook.application")
Resume Next
End Sub
Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2010
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
Why do you explicitly specify the version? Why not simply
Set emailOutlookApp = CreateObject("Outlook.Application")
Try "Outlook.Application.14". Not sure if this is related though: 2007 to 2010 upgrade issue
I realize it's not the exact issue, but it may lead you down the right path.

Resources