Unable to paste into a protected worksheet using VBA, but can do it manually - vba

I have written a macro that should copy a range of data from one workbook into another. The sheet in the other workbook is password protected, but if I copy and past manually, it allows me to do so. However, when I try and write this into my macro, it won't allow the paste.
Code is currently as follows:
Sub COPYT()
'
' COPYT Macro
Range("B2:U109").Select
Selection.Copy
Workbooks.Open Filename:= _
"_FileName_.xls"
Windows("_FileName_.xls").Activate
Range("H10").Paste
End Sub
When I run the macro as is, I get a
Run-time error '438': "Object doesn't support this property or method"
and the debugger shows that the issue is with the last line Range("H10").Paste
I can't unprotect the sheet (compliance), and I can obviously get round this by just running the macro and then CTRL+V but (as this allows me to paste....), but I would rather that this was automated. Do I need a different syntax for the paste command due to the sheet being protected?
Thanks

Paste is a method of the worksheet, not range. Try this. I have assumed sheet references but you may need to adjust.
Sub COPYT()
Dim wb As Workbook
Set wb = Workbooks.Open(Filename:="_FileName_.xls")
wb.Sheets("compliance").unprotect
ThisWorkbook.Sheets(1).Range("B2:U109").Copy wb.Sheets("compliance").Range("H10")
wb.Sheets("compliance").protect
End Sub

Related

How to run a macro from a different workbook in a shared network?

So, I've done a lot of research on this and my code isn't working still. As per the title, the problem is this:
I pull a data report off of a website, this report is downloaded as an .xlsx file. I created a macro on the ribbon so I when I click it, it will then open another workbook and run that macro. The code I'm using is as below:
Option Explicit
Sub NotHardAtAll()
Dim ws As Worksheet,
Dim wb As Workbook
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Workbooks.Open Filename:="C:\Users\a0c27n\Desktop\Projects\incident_extended_report1.xlsm"
'With Sheets("Sheet4").Activate '*Not sure if this is enter code here
necessary...at all*
Application.Run "!ADDHMKRFID"
'End With
End Sub
I've tried putting the path before the macro (i.e. Application.Run"'incident_extended_report1.xlsm!ADDHMKRFID") but it doesn't work either*
I'm aware, at least form the research I've done, that I should be able to just use the 'Application.Run' Method, however I couldn't get it to access the correct sheet.
When I run the Macro, it pulls a Run-time error '1004' error, a '400', or the it pulls the most is: "Cannot run the macro '!ADDHMKRFID'. The macro may not be available in this workbook or all macros may be disable."
The file that I'm trying to pull the macro from is below:
Workbook name: incident_extended_report1.xlsm
Worksheet name: Sheet4 (TEST MACRO)
Macro Name:
Sub ADDHMKRFID()
End Sub
I understand that the C:\ is not a shared network, the one I will be working out of will be the S:\, however I'm not sure how much information I can post due to confidentiality.
Please ask for any clarification or questions you may have. I've been stuck for a bit and am not sure what I'm doing wrong. Thanks in advance!
The string you need to pass to Application.Run depends on whether the workbook containing the macro is active, and if it isn't, the filename of the macro-containing workbook (IE: what's in the workbook.Name property).
if the macro is supposed to be run while the data report workbook is active, you want:
dim wb_data as Workbook: set wb_data = ActiveWorkbook
dim ws_data as Worksheet: set ws_data = ActiveSheet
dim wb_macro as Workbook
set wb_macro = Workbooks.Open(Filename:="C:\Users\a0c27n\Desktop\Projects\incident_extended_report1.xlsm")
ws_data.Activate
Application.Run wb_macro.Name & "!ADDHMKRFID"
This will guarantee that the correct string is supplied, even if you change the name of the macro file.
Otherwise, if the macro workbook is supposed to be active, skip activating the data worksheet, as the last opened workbook will be active by default, then use "ADDHMKRFID" as your string. Note that the "!" is missing. You need that only if you are specifying a macro in another workbook. It's the same kind of notation used when referring to data in other worksheets.
First of all, I solved my own problem. I would, however, be grateful if someone might explain to me why it worked the way it did.
I saved the original macro on the shared network, but I had to save it as a module (in this case Module1). I also saved the 2nd macro (to run the original one) in a different workbook (though it shouldn't matter, as long it is not a .xlsx file).
The Code I wrote was:
Sub Test() 'Name doesn't matter
Application.Run "'S:\xxxx\xxxx\xxxx\incident_extended_report.xlsm'!module1.ADDHMKRFID"
End Sub
Then I saved this macro to the ribbon so I could run it on the data report.xlsx file I have to download. Now, anytime I want to run the original macro, I just click the Test Macro, and it'll run the other one!
I'm guessing if you want to close the other workbook that you opened, you can just add a
Workbooks (“S:\xxxx\xxxx\xxxx\incident_extended_report.xlsm").Close Savechanges:=False
Good Luck!

Excel VBA copy Run-Time error '1004'

I can't figure out what's wrong with my VBA:
Private Sub CommandButton4_Click()
Sheets("Opgave").Select
Range("F9:G14").Select
Selection.Copy
Sheets("Reserve").Select
Range("E3").Select
End Sub
Excel says Range("F9:G14").Select is wrong!
You need to Activate the sheet, because Range is implicitly referring to the active worksheet, and you're wrongly assuming Selecting something will necessarily Activate it.
I've executed your code with "Sheet1" and "Sheet2" without any error being thrown, "Sheet1!F9:G14" selected for copy and "Sheet2!E3" selected, which seems to be what this code wants to achieve.
Still, I'd like to say...
Avoid problems, avoid Select and Activate in VBA code.
Sheets have a CodeName property that you can change from, say, Sheet1 to OpgaveSheet, or Sheet2 to ReserveSheet. Then this code is valid:
OpgaveSheet.Range("F9:G14").Copy ReserveSheet.Range("E3")
The Name of a worksheet is the text that's displayed in the tab for it in Excel. You can also use that to get a reference to a worksheet:
Dim opgaveSheet As Worksheet
Set opgaveSheet = ThisWorkbook.Worksheets("Opgave")
Dim reserveSheet As Worksheet
Set reserveSheet = ThisWorkbook.Worksheets("Reserve")
And when you want to work with a specific range, keep a reference to it instead of Selecting it and working with the Selection:
Dim source As Range
Set source = opgaveSheet.Range("F9:G14")
Dim destination As Range
Set destination = reserveSheet.Range("E3")
source.Copy destination
Code that doesn't constantly interact with worksheets (via Select and Activate) is going to perform better, will be easier to follow, debug and maintain, and will be much less error-prone.

Saving/restoring clipboard in Excel VBA

I have an Excel workbook with many sheets. Most sheets have some code in the Worksheet_Activate() subroutine.For some reason this code causes the contents of the clipboard to be lost - extremely annoying, as spreadsheet user cannot copy and paste between sheets.
In an attempt to fix this I have added the following lines at the beginning of the Worksheet_Activate code:
Dim dClipBoard As MsForms.DataObject
On Error Resume Next
Set dClipBoard = New MsForms.DataObject
dClipBoard.GetFromClipboard
And the following lines just before exit of the Worksheet_Activate code:
On Error Resume Next
dClipBoard.PutInClipboard
Unfortunately, it doesn't work. My clipboard is still lost when I move from sheet to sheet.
I can imagine 2 different workarounds for this case.
1- If possible change the code in the worksheets. Where ever the .copy command is used replace it with codes like these:
range("Some Range") = range("Some other range")
2- If changing the code is not possible (using the approach you are currently using) instead of storing the data to an MsForms.DataObject you could copy them to some auxiliary sheet, And retrieve the data from the worksheet before the exit worksheet event triggers.

Select worksheet in Excel add-in to run VBA macro

I have created an add-in using VBA which is a workbook with calculations. The add-in has a userform to extract relevant information from access database and populates the workbook. After the data is populated, calculations are performed in Sheet1. I need to paste the worksheet "Sheet1" from the add-in worksheet to a new workbook on running the add-in macro.
When I run the add-in however, the worksheet appears to be hidden so my data is not updating. I get this error:
" Run-time error '1004': Method 'Worksheets' of object '_Global' failed".
Can someone tell me how to work with an add-in which has a worksheet where the required calculations are performed?
The intriguing part is when I load the add-in after removing it from the list of add-ins in excel, it runs perfectly. But when I re-run the macro, the worksheet becomes hidden, so the same error appears. I am fairly new to VBA so any suggestions would be appreciated!
Edit
Code:
Private Sub OptionOK_Click() 'On selecting OK from userform
Dim ws1 As Worksheet
Sheets("Sheet1").Visible = True
Set ws1 = Worksheets("Sheet1")
'User Form Validation
If Trim(Me.cboData.value) = "" Then
Me.cboData.SetFocus
MsgBox "Please complete the form"
Exit Sub
End If
'copies data to given cell in excel
ws1.Range("A1").value = Me.cboData.value
'To copy selection from "Sheet1" into new workbook
Workbooks("myaddin.xlam").Sheets(1).Copy
End Sub
I get the error on ...> Sheets("Sheet1").Visible = True.
I just realized that I had to use "ThisWorkbook" in the add-in VBA code.
Set ws1 = ThisWorkbook.Sheets ("Sheet1")
VBA code within a workbook should use "ThisWorkbook" to reference to sheets or ranges inside the add-in.
If you know what sheet it is and you have access to the add-in code just make sure it's visible before the line that throws the error.
Sheets("Sheet3").Visible = True
I suspect you have another problem though because you can still reference a hidden sheet in code.
Are you sure this line is correct:
Workbooks("myaddin.xlam").Sheets(1).Copy
Before you were referencing the name of the sheet now your referencing the position of the sheet in the workbook.

Excel 2010 VBA running in all opened files

I have one excel file (*.xlsm) with VBA code on first sheet:
Private Sub Worksheet_Calculate()
ActiveSheet.ChartObjects("Podtlak").Chart.Axes(xlCategory, xlPrimary).MaximumScale = Range("AV79").Value
End Sub
And second excel file with macro that is changing value in cell in first excel (it is automaticaly recalculated) and then copy value of new result from first excel and paste it to second excel file.
Problem is: when macro is going to second excel and paste value, worksheet is recalculated and code from first excel is calling, but it stops with error because in second excel it cant find chart object "Podtlak".
How to set worksheet_calculate() to run only for file whitch one is it written?
Try specifying the workbook:
ThisWorkbook.ActiveSheet.ChartObjects("Podtlak").Chart.Axes(xlCategory, xlPrimary).MaximumScale = Range("AV79").Value
Or specifying the worksheet and workbook:
ThisWorkbook.Worksheets("yourWorksheetName").ChartObjects("Podtlak").Chart.Axes(xlCategory, xlPrimary).MaximumScale = Range("AV79").Value
I like the 2nd option best as you are clearly specifying the worksheet and workbook that this function runs on. Anytime you use ActiveSheet or ActiveWorkbook, you are relying on the fact that your intended worksheet is active when the code runs.