VBA MACRO unable to paste - vba

Please help me... this is driving me nuts.
I am trying to copy some data from a CSV but unable to paste it to the destination file that I normally do manually.
The issue I am facing:
-I cannot go back to the destination file's sheet
-Even if I could it would paste as string
-I need the data to be identical from the CSV
MyFile = Application.GetOpenFilename()
ChDir "C:\datafolder\"
Application.Workbooks.Open (MyFile)
Range("A1").CurrentRegion.Select
Selection.copy
ActiveWorkbook.Close savechanges:=False
Application.ScreenUpdating = True
Windows("chickenfeed.xlsm").Activate
ActiveWorkbook.Sheets("Raw Export").Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End sub

You closed the source range before the paste.
Try this and learn the flow...
(Assuming it's "Sheet1" you try to copy data from)
Option Explicit
Sub PasteData()
Dim oSourceWB As Workbook, oTargetWB As Workbook, MyFile As String
MyFile = Application.GetOpenFilename()
ChDir "C:\datafolder\"
On Error Resume Next
Set oSourceWB = Workbooks.Open(Filename:=MyFile, ReadOnly:=True)
Set oTargetWB = Workbooks("chickenfeed.xlsm")
On Error GoTo 0
If Not (oSourceWB Is Nothing And oTargetWB Is Nothing) Then
oSourceWB.Worksheets("Sheet1").Range("A1").CurrentRegion.Copy oTargetWB.Sheets("Raw Export").Range("A1")
oSourceWB.Close SaveChanges:=False
End If
Set oSourceWB = Nothing
Set oTargetWB = Nothing
End Sub

Related

How do I save an Excel file as CSV using VBA whereby the new file won't give me an error message?

I know there are similar questions (and answers) on Stack Overflow but I'm specifically trying to prompt the end user to save the file and rename it as appropriate, not have the file automatically created.
I'm trying to create a macro that will automatically export a worksheet in my workbook and save the file for non-technical users, as a CSV. The macro actually works fine, but each file it creates gives me the error message "The file format and extension of 'NAME OF FILE.csv' don't match. The file could be corrupted or unsafe. unless you trust its source, don't open it. Do you want to open it anyway?" How can I have this new file open up without this warning message? Here's my code:
Sub copy_translated_file()
Dim DstFile As String 'Destination File Name
Dim wb As Workbook
Dim InitFile As String
InitFile = "BE SURE TO CHANGE THE NAME OF THIS FILE TO WHAT YOU WANT.csv"
Sheets("Translated").Select
Sheets("Translated").Copy
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Set wb = ActiveWorkbook
ActiveSheet.Buttons.Delete 'Get rid of the macro button
Columns("N:N").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Delete Shift:=xlToLeft
Range("F1").Select
DstFile = Application.GetSaveAsFilename(InitialFileName:=InitFile, _
fileFilter:="CSV (*.csv), *.csv", _
FilterIndex:=1, _
Title:="Save As")
If DstFile = "False" Then
MsgBox "Actions Canceled. File not saved."
wb.Close savechanges:=False 'Close File
Exit Sub
Else
wb.SaveAs DstFile 'Save file
wb.Close False 'Close file
MsgBox ("Translated file successfully saved in specified location.")
End If
End Sub
That is a setting in Excel itself, going to File -> Options -> Trust Center
Also, ensure your flag is set for FileFormat:=xlCSV

Paste Special VBA does not work in embedded excel workbook

I'm having an issue with the PasteSpecial function when working in an embedded excel workbook. The program I am working in is "Promax" which is block diagramming software running in Visio, which has the option to add an embedded excel workbook. I've essentially set up a number of cells in excel so that I can import a bunch of fields into a PDF form.
While working in the embedded workbook I am unable to get this function to give any output into the new excel worksheet. If I save a version of the workbook that is outside of promax, the code runs fine. If I just try to paste instead of paste special the code works fine, but all of the references that I pasted break in the new workbook.
Sub ExporttotxtFile()
Dim wb As Workbook
Dim saveFile As String
Dim WorkRng As Range
On Error Resume Next
Set WorkRng = Sheets("Sheet1").Range("A1:HK2")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set wb = Application.Workbooks.Add
WorkRng.Copy
wb.Worksheets(1).PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
wb.Worksheets(1).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
saveFile = Application.GetSaveAsFilename(InitialFileName:="Export", fileFilter:="Text Files (*.txt), *.txt")
wb.SaveAs Filename:=saveFile, FileFormat:=xlText, CreateBackup:=False
wb.Close
Application.CutCopyMode = False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Does anyone have a solution to this or another method of getting this done? This code was taken from this: https://www.extendoffice.com/documents/excel/612-excel-export-data-to-text.html
Thanks!
While playing around with this more it seemed like xlPasteFormat was pasting an image over the values rather than formatting. I scrapped the pastespecial method and used a different solution.
wb.Worksheets(1).Paste
wb.Worksheets(1).Range("A1:HK2").Value = WorkRng.Value
I paste everything with the first paste and set the values with the second line so that the formatting stays.
Thanks for the help everyone.

Excel set active Workbook

I searched the forum and couldn't find an answer that would fit my problem. I am pretty new to Excel VBA and am having trouble activating a workbook I just opened. Directly below is the part that is causing me trouble.
So I press a button and it brings me to the file path, and I select a file to open. Every week this file has a different name and I am not really sure what it is until I open the file path and look at it.
Once I open it, I would like my macro to manipulate the data in the file and copy and paste into the workbook running the code. However when I run this macro and open the file it will not activate the newly opened workbook and runs the rest of the macro trying to manipulate the data in the original file.
I think I either need to open the file differently so that the workbook I just opened is the active one or figure out how to activate the newly opened workbook without knowing the file name. Thank you for your help.
Dim filepath As String
filepath = Environ("USERPROFILE") & "\Dropbox\On the go ordering"
Call Shell("explorer.exe" & " " & filepath, vbNormalFocus)
Range("A6:E500").Select
Sub on_the_go_button()
Dim RANKER As Workbook
Set RANKER = ThisWorkbook
Dim filepath As String
filepath = Environ("USERPROFILE") & "\Dropbox\On the go ordering"
Call Shell("explorer.exe" & " " & filepath, vbNormalFocus)
Range("A6:E500").Select
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.AutoFilter
ActiveSheet.Range("$A$1:$E$495").AutoFilter Field:=1, Criteria1:=RGB(213, _
223, 248), Operator:=xlFilterCellColor
Range("G1").Select
ActiveCell.FormulaR1C1 = _
"=IF(RIGHT(RC[-6],8)=""Subtotal"",VALUE(LEFT(RC[-6],6)),"""")"
Range("H1").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]="""","""",RC[-4])"
Range("I1").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]="""","""",RC[-4])"
Range("G1:I1").Select
Selection.Copy
Range("G1:I500").Select
Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Selection.Copy
RANKER.Activate
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("P1:Q74").Select
Selection.Copy
Sheets("Contest").Select
Range("A3").Select
ActiveCell.End(xlToRight).Select
ActiveCell.Offset(0, 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
Because the OP specified a default path; I recommend using the Application.FileDialog(msoFileDialogFilePicker)
USAGE:
Dim WeeklyWorkbook
Set WeeklyWorkbook = getWeeklyWorkbook
If WeeklyWorkbook Is Nothing Then
MsgBox "No file selected", vbInformation, "Action Cancelled"
Exit Sub
End If
Function getWeeklyWorkbook() As Workbook
Dim fDialog As FileDialog, result As Integer
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
'Optional: FileDialog properties
fDialog.AllowMultiSelect = False
fDialog.Title = "Select a file"
fDialog.InitialFileName = Environ("USERPROFILE") & "\Dropbox\On the go ordering"
'Optional: Add filters
fDialog.Filters.Clear
fDialog.Filters.Add "Excel files", "*.xls, *.xlsx, *.xlsm"
fDialog.Filters.Add "All files", "*.*"
'Show the dialog. -1 means success!
If fDialog.Show = -1 Then
Set getWeeklyWorkbook = Workbooks.Open(fDialog.SelectedItems(1))
End If
End Function
Reference: VBA FILEDIALOG – OPENING, SELECTING AND SAVING FILES AND FOLDERS
Try below...
filepath = application.getopenfilename()
Dim Wb as workbook
Set Wb = workbooks.open(filepath)
Use WB as workbook object

Copy data from a selected excel file

I am trying to construct a macro that when run will allow me to select a given file and check the data in Column C of that selected file. I am very new to VBA and have only rudimentary skills. I have all the parts of my code working except for the portion where I pull in the data from the variable file and paste it into column A of my macro file for the review functions to perform.
I have cobbled together the below code to populate the data from Column C of any given selected file into Column A of the macro file from what I could piece together from searching through the site, but I am still getting an error 400 after selecting the file to open when running this Sub. Would appreciate any assistance with figuring this portion out.
Thanks!
Sub PopulateUploaderFunds()
'Pull in funds from uploader to be reviewed for custody and mirror accounts
Dim uploadfile As Variant
Dim uploader As Workbook
MsgBox ("Please select uploader file to be reviewed")
uploadfile = Application.GetOpenFilename()
If uploadfile = "False" Then
Exit Sub
End If
Workbooks.Open uploadfile
Set uploader = ActiveWorkbook
With uploader
Application.CutCopyMode = False
Range("C1").End(xlDown).Select
Selection.Copy
End With
Windows("Test Mirror Macro Build Test.xlsm").Activate
Sheets("Sheet1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
It looks like a problem with how you are navigating between workbooks, try this:
Sub PopulateUploaderFunds()
'Pull in funds from uploader to be reviewed for custody and mirror accounts
Dim uploadfile As Variant
Dim uploader As Workbook
Dim CurrentBook As Workbook
Set CurrentBook = ActiveWorkbook
MsgBox ("Please select uploader file to be reviewed")
uploadfile = Application.GetOpenFilename()
If uploadfile = "False" Then
Exit Sub
End If
Workbooks.Open uploadfile
Set uploader = ActiveWorkbook
With uploader
Application.CutCopyMode = False
Range("C:C").Copy
End With
CurrentBook.Activate
Sheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub

Simple Excel VBA macro failing

I have the following simple macro to copy data from a closed worksheet. The code runs fine from the VBA editor but fails with a subscript error when run from Excel via macro. The paste special statement appears to be the issue.
I just can't see where the problem is, can anyone help?
Dim wsMaster As Worksheet
Set wsMaster = Worksheets("Master Data")
Dim lastrow As Long
Dim Files As String
Files = "Download.xlsx"
Dim filepath As String
filepath = "C:\users\ms612533\desktop\"
Application.ScreenUpdating = False
wsMaster.Activate
Cells.Select
Selection.Clear
Workbooks.Open (filepath & Files)
lastrow = Worksheets("Global").UsedRange.Rows.Count
Worksheets("Global").Range("A1:V" & lastrow).Copy _
wsMaster.Range("B1")
Worksheets("Global").Range("CV1:cv" & lastrow).Copy
wsMaster.Range("a1").PasteSpecial (xlValues)**
Application.CutCopyMode = False
ThisWorkbook.Activate
Call CloseAll
Application.ScreenUpdating = True
End Sub
Sub CloseAll()
' Close all but the active workbook
Dim wkbk As Workbook
Application.ScreenUpdating = False
For Each wkbk In Application.Workbooks
If wkbk.Name <> ActiveWorkbook.Name Then
wkbk.Close SaveChanges:=False
End If
Next
Application.ScreenUpdating = True
End Sub
I think there's something wrong with the PasteSpecial line: when I use the macro recorder, I get something like this:
wsMaster.Range("a1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
I think we can ignore the parameters after the first. Then we have this:
wsMaster.Range("a1").PasteSpecial Paste:=xlPasteValues
Note that there are no parens (()) around the arguments: PasteSpecial doesn't return anything so it should be treated like a function. That's probably where the subscript issue is coming from.
Also notice the parameter, which comes from the xlPasteType enum, is a little different from the value you had.
The code appears to work fine when calling the macro from a button, but it doesn't work from a shortcut. I'll put it down to an Excel 'feature' and move on.