VBA Copy and Paste SQL Data as Values in Excel Spreadsheet Not Pasting - vba

I have written a code which open a worksheet that contains a SQL data connection, I then refresh the data, copy the values and attempt to paste that information into the original spreadsheet.
the data does not paste, however, if i manually step through the code hitting F8 the data pastes - i can't figure out why this is -
if this is an easy question my apologies, I am new to VBA, I asked around my office and searched google - still can't find an answer - here is the code
Sub getdata()
'
' getdata Macro
'
' Keyboard Shortcut: Ctrl+a
'
' make holdings report tab visible and clear the contents
Sheets("Holdings Report").Visible = True
Sheets("Holdings Report").Activate
Range("A2:J65536").Select
Selection.ClearContents
' open the original holdings report, refresh data, copy data
Workbooks.Open "\\hcc-fileprint\sys\Share\Institutional Group\Rebalancing\HCNet Update.xlsm"
Sheets("Sheet1").Activate
Application.Wait Now + TimeValue("00:00:02")
ActiveWorkbook.RefreshAll
Application.Wait Now + TimeValue("00:00:02")
ActiveWorkbook.RefreshAll
Range("A2:J65536").Select
Selection.Copy
'activate the rebalancing spreadsheet paste the values and then hide the tab
ThisWorkbook.Activate
Sheets("Holdings Report").Activate
Range("A2").Select
ActiveSheet.paste
End Sub

Could it be that you're actually not copying anything, because the database query started with RefreshAll is running in the background and has not returned any data by the time you reach Copy?
I see that you're waiting 2 seconds, but that might simply not be long enough, whereas single-stepping gives Excel more time to get the data.
Unfortunately, there doesn't seem to be a specific event that you could react to when RefreshAll has completed, which would be the "right" way of going about it. Perhaps Workbook.SheetChange is fired though; you could try that.
Just a shot in the dark, really, but the copy/paste code itself doesn't seem wrong, and you didn't say that you get any errors.

Need to Modify the paste command to paste the values.
ActiveSheet.PasteSpecial xlPasteValues

Related

Sheet inaccessible to macro: Error 1004: Application/Object Defined Error

This is happening in several of my macros, but this is the one in from of me:
Private Sub resettool()
'''resets step 2 input and user input on MPP tabs
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Call showsheets 'makes all of these sheets .Visible = True
'clear data from lookups and data corrals
Sheets("Media by Copy Lookup").Range("b1",Range("b1").End(xlToRight).End(xlDown)).ClearContents
Sheets("Total Media Lookup").Range("d1",Range("d1").End(xlToRight).End(xlDown)).ClearContents
Sheets("Total Media Lookup").Range("b2:c100").ClearContents
Sheets("Media by Copy Data").Range("a1",Range("a1").End(xlToRight).End(xlDown)).ClearContents
'etc etc
End Sub
It continues with similar data-clearing lines for a while. This started happening when I took someone else's code and cleaned it by removing the .Select usages as people on here have suggested. It seems that the macro isn't able to access the sheets I'm referencing, because a line runs successfully if I step into the code, manually select the referenced sheet, and then hit go (but then of course I get the same error when I try to edit another sheet).
Any ideas why the macro wouldn't be able to access these sheets unless I explicitly activate/select them? The sheets are all visible, so that shouldn't be the problem.
P.S. I've seen the guide on using .Rows.Count).End(xlUp) instead of End(xlDown) to find the bottom of my data and will implement that soon, but this issue is occurring no matter how I define the range; it's about the sheet.

VBA Paste function throwing error after VBA Clear function

I have an advanced filter that is being used to sort a large data set.
The filter is dropping the filtered data into a separate sheet.
I have a VBA Macro that allows me to highlight the portions of the filter that I want to use and paste it into a range adjacent to the filter table.
Currently I am using very simple VBA.
The copy of the active selection and paste into the next open row after a specified Cell. The cell is a row of headers that corresponds to the headers of the table that the copy selection is being made from.
Sub CopyPaste()
Selection.Copy
ActiveSheet.Range("J6").End(xlDown).Offset(1, 0).Select
ActiveSheet.Paste
End Sub
The clear is very simple.
Sub ClearTable()
ActiveSheet.Range("J7:O100").Clear
End Sub
After the clear is run, I receive an error.
Get Run Time error '1004, Application-defined or object defined error.
EDIT: Clarification. .clear and .clearcontents both lead to the errored state If I attempt to paste after I clear the range.
With J7:O100 cleared, select J6 and tap [ctrl]+[down arrow]. Try and go one more row further down. That is where you are trying to paste and if you follow my directions the problem should be perfectly obvious.
Use,
Selection.Copy Destination:=ActiveSheet.Cells(Rows.Count, "J").End(xlUp).Offset(1, 0)
This looks from the bottom up and selects 1 row down not from the top down (which seems to be J1048576 and cannot be moved down a row let alone having room for the paste).

Macro Copy&Paste

I'm trying to create a macro that will copy data from one worksheet and place into another. This I can do with no problem. But, when I want to use the same macro in another row is where I have my problem. Basically what I want to do is copy cell D11 from sheet1 and place that in cell B4 on sheet2, etc (What I'm doing is obviously more complicated than that, but that doesn't matter here).
My problem is when I want to now run this macro and copy cell D12 from sheet1 and paste into B5 on sheet2 the value pasted jumps to B4. I understand that this happens because of where the VBcode is saying to paste the copied value.
My question is how to I just have it paste in whatever row I choose? Maybe based on what row/cell I have selected.
Current code, written by recording the macro
Sheets("sheet1").Select
Range("D11").Select
Selection.Copy
Sheets("sheet2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("B4").Select
I'm assuming the last line is where I need to make the change, but I'm not sure what to change.
Thank you! Any and all help is greatly appreciated.
As a general rule, try to avoid Selection Copy-Paste (detailed discussion is provided in: "Application.Calculation = xlCalculationManual" statement causing run-time error 1004 in VBA Copy-Paste procedure). Instead, use direct copy statement, which will solve you issue and significantly improve performance:
Listing 1.
Sub DirectCopySample()
Application.ScreenUpdating = False
Sheets("Sheet1").Range("D11").Copy Destination:=Sheets("Sheet2").Range("B5")
Application.ScreenUpdating = True
End Sub
Sub in Listing 1 performs direct copy from Cell: Sheets("Sheet1").Range("D11") into cell: Sheets("Sheet2").Range("B5").
Also, your initial Copy-Paste Sub could be simplified (it will also make it work, though Listing 1 is preferred)
Listing 2.
Sub CopyPasteSample()
Sheets("sheet1").Range("D11").Copy
Sheets("sheet2").Range("B5").PasteSpecial Paste:=xlPasteValues
End Sub
Hope this will help. Best regards,
You seem to have recorded a Macro and are trying to replay it. Here is a real VBA code (not a Macro recording type):
Sheets("sheet2").Range("B5") = Sheets("sheet1").Range("D11").Value
This is all!
BTW, your predicament comes from the fact that the PasteSpecial method copies into the currently selected cell. You've tried running this Macro several times and the Range("B4").Select line did the trick. If you insist on your approach the insert Range("B5").Select BEFORE the PasteSpecial.

Copy data from multiple excel sheets and append that to a single excel sheet using VBScript

The scenario is as follows:
I have an excel (.xls) file with data. (eg. A.xls)
The Data on this excel file are on a single worksheet (Sheet 1).
The number of columns in this file is fixed i.e. 8
However, the number of rows containing data may vary from time to time. (This file is updated by another program from time to time)
Now, I have another excel file (eg. B.xls) with similar type of data but not same as the contents of A.xls.
The number of columns in B.xls is 8 as well. However, the number of rows containing data are unknown.
I want to copy the contents of A.xls, 2nd row onwards (excluding the 1st row containing the column headers) and append/paste the same to the B.xls file, without over-writing the existing data on B.xls.
With all these details in mind, I want to write a vbscript to automate this task.
Please help.
Thanks a lot, in advance.
It needs a lot of cleanup, but something like this should work. I'll clean it up a bit and then make an edit.
Sub CopyRows()
' Choose the name of the Second Workbook and last column.
' It must be in the same directory as your First Workbook.
secondWorkbook = "B.xls"
lastColumn = "H"
' A couple more variables
currentWorkbook = ThisWorkbook.Name
Workbooks.Open ThisWorkbook.Path & "\" & secondWorkbook
' In the First Workbook, find and select the first empty
' cell in column A on the first Worksheet.
Windows(currentWorkbook).Activate
With Worksheets(1).Columns("A:A")
Set c = .Find("", LookIn:=xlValues)
If Not c Is Nothing Then
' Select and copy from A2 to the end.
secondAddress = Replace(c.Address, "$A$", "")
Range("A2:" & lastColumn & CStr(CInt(secondAddress) - 1)).Select
Selection.Copy
End If
End With
' Activate the Second Workbook
Windows(secondWorkbook).Activate
With Worksheets(1).Columns("A:A")
Set c = .Find("", LookIn:=xlValues)
If Not c Is Nothing Then
' Select and paste the data from First Workbook
Range(c.Address).Select
ActiveSheet.Paste
End If
End With
End Sub
Update: That should do the trick. I copied from the wrong workbook the first time around, too. Let me know if you have questions.
This is something the Macro Recoder could have written for you. You would come out with different approach.
Turn on recording. Open A.xls and B.xls. Move down one row on a. Press Shift+End then →, then Shift+End+↓. Then Ctrl+C to copy your data. Switch back to B. End+↓, ↓. Ctrl+V to paste. Turn off recording.
You can record in Excel.
Alt+T,M,R
then Home key then ↑. Stop recording.
Look what Excel wrote
Selection.End(xlUp).Select
or if you had of recorded Go To dialog
Application.Goto Reference:="R1C1"
or if you had of recorded Ctrl+Home
Range("A1").Select
To convert to vbscript
Record the steps in excel macro recorder. You have to rewrite it a bit because it uses a type of syntax that vbs doesn't.
This applies (I don't have a medium9) xlRangeAutoFormatAccounting4 in vba.
Selection.AutoFormat Format:=xlRangeAutoFormatAccounting4, Number:=True, _
Font:=True, Alignment:=True, Border:=True, Pattern:=True, Width:=True
So first look up constants in vba's object browser. xlRangeAutoFormatAccounting4 = 17
Then look the function up in object browser and look at the bottom for the function definition,.
Function AutoFormat([Format As XlRangeAutoFormat = xlRangeAutoFormatClassic1], [Number], [Font], [Alignment], [Border], [Pattern], [Width])
So the vba becomes in vbs (and vbs works in vba) (and as you can see you can work out the correct way without needing to look the function up usually)
Selection.AutoFormat 17, True, True, True,True, True, True
So your code becomes
objXLWs.Range("A3").CurrentRegion.Select.AutoFormat 17, True, True, True,True, True, True

Excel 2010 Macros Fun with Buttons

Ok so I am creating a spreadsheet that can be edited by another user but locked otherwise. What I am hoping to do is create 3 buttons. "What If" "Exit What if" and "Reset"
"What if" will allow for the user to input data.
"Exit what if" will allow for the user to exit the input mode and revert back to the default. document.
Then "Reset" will allow for the user stay in "What if" but reset all the values to default.
Then I want the button "What if" to appear somewhere up in the left but when you click it, its replaced by "Exit" and "Reset"
I suggest you to explain a little more you question, but so far for what I can infere you have the folloing issuse:
have a excel sheet with formulae and data locked.
offer edit the page, but no save the changes, as "a consult" to the data.
I can primarily offer the following:
Create a backup sheet where your save you base page
Unlock the sheet for editing.
if you exit the editing, restore the data from the backup to the main sheet.
if you reset the editing, do the same procedure as exit plus unlock again the data. (for how it was charted the code flow, the copied sheet has his data locked)
This will result in the followin code:
Sub BackUpData() 'this will be linked to you "what if" button
Sheets("Data_Sheet").Select 'select shhet with data, just in case
Range("A1:M56").Select ' range of your important data in your excel sheet
Cells.Select
Selection.Copy
Sheets("BackUp_Sheet").Select
Range("A1").Select 'lets paste the data in the same positión
ActiveSheet.Paste
Application.CutCopyMode = False
Sheets("Data_Sheet").Select
End Sub
This make a copy of the data and the formulas, copying charts without breaking his datasource is another problem, maybe your can elabore on this matter. Have any charts?
Sub RestoreData() 'this will be linked to you "Reset" and "Exit" button
Sheets("BackUp_Sheet").Select 'select shhet with data, just in case
Range("A1:M56").Select ' range of your important data in your excel sheet
Cells.Select
Selection.Copy
Sheets("Data_Sheet").Select
Range("A1").Select 'lets paste the data in the same positión
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub
Usual room for improvement:
Dinamicaly select the range, but no select all the sheet, because memory isssuses may arise. (I run out of resources when try to copy all the cell of excel 2007 in my laptop :P).
Remove flicker with Application.ScreenUpdating.
I haven`t check if this work when the *backup_Sheet* is hidden.
The other isssuse is unlock the data in the sheet.
Sub UnlockMySheet()
'password here won`t protect the business logic or the code from prying eyes, just the user from themselves
ActiveWorkbook.Unprotect
ActiveSheet.Unprotect
Range("D9,B13").Select ' select the editable cells
Selection.Locked = False
Selection.FormulaHidden = False
ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
ActiveSheet.EnableSelection = xlUnlockedCells
ActiveWorkbook.Protect Structure:=True, Windows:=True
End Sub
Usual room for improvement:
Maybe I forgot the protect protocol and I`m just leaving the page exactly as it was. (sorry no time to proof this code).
Sugestion from stackoverflow collective mind.
and that is, for now