VBA, active sheet issue - excel

I am trying to transfer selected data from one worksheet to another via a Transfer macro.
Every time I try to do so, I get the following message in Debug:
Sub Transfer Macro
ActiveCell.Offset(-10, -7).Range("A1").Select
Selection.Copy
Sheets("Data Presentation Template").Select
ActiveCell.Offset(-25, -6).Range("A1").Select
ActiveSheet.Paste
End Sub
Is there a better way to transfer/ mirror the data from a data entry sheet to a presentation sheet with out macro?

Your ActiveCell.Offset(r, c) commands use negative numbers. These will depend on whether the currently active cell is in a position where the negative offsets don't try to .Select a cell that is either off the worksheet to the left of column A or a cell that is above row 1.
ActiveCell.Offset(-10, -7).Range("A1").Select
This demands that the ActiveCell is at least 10 rows down and 7 columns right from A1; specifically K8 or to the right/down of K8. Anything closer to A1 will produce an error since you are trying to select a cell that is off the worksheet.
ActiveCell.Offset(-25, -6).Range("A1").Select
The same for this statement but the minimal distance for the ActiveCell from A1 would be Z7.
The ActiveCell property changes every time you select another cell. It cannot be relied upon to 'automatically transfer' data between worksheets unless you check to ensure that the ActiveCell is where you want it on each worksheet before running your sub procedure.
Any further recommendations would require specific worksheet names and ranges for the source and target of the copy & paste operation.
The .Range("A1") in ActiveCell.Offset(-10, -7).Range("A1").Select simply means the top-left cell in the ActiveCell.Offset(-10, -7) range. It is likely a 'hangover' from relative positioned macro recording.

Related

Copy a specific range every nth number of rows in Excel VBA

I'm very new to VBA coding and cannot figure out this issue. I tried another solution but found it wouldn't work later down the road. I'm currently testing out this one.
On worksheet "BS growth" I need to read Column A to make sure it says "Asset" If it does I then need to copy and paste the entire rows, excluding A,B & C starting from D5 until D30. The loop then needs to skip 15 cells down and copy the next range of 25 rows (D45:D70, D85:D110, etc) until it no longer says Asset in column A. The first 402 rows in Column A say "Asset," and then the next 300 say "Liability" and the final 200 says "Equity."
I'll then need to paste the data into worksheet "Chart Ref" starting at row A2.
Here is a sample of the data. I am not sure if it is working/embedded properly.
enter image description here
I do not know how to make a loop repeat as needed.
Sub ChartReference4()
Dim ws As Worksheet
Set ws = ActiveWorkbook.Worksheets("BS growth")
For Each cell In ActiveWorkbook.Worksheets("BS growth").Range("A:A")
If cell.Value = "Asset" Then
Range("D5:D30").Select
'I need this to not be hard coded and only copy from D5 down 25 and then skip 15 cells and repeat the loop
Range(Selection, Selection.End(xlToRight)).Select 'Need all information to right
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Worksheets
End If
Next cell
End Sub
Currently this code just copies everything in the sheet from column D to the right.
Thanks so much, please comment if this doesnt make sense or I need more information.

Find cell & select/copy from active cell to last row including blanks

I'm attempting to find a column using the column header name, then select all the data from the column (including the blank cells) & paste into another range.
Currently I can only copy until the 1st blank cell. I have seen similar problems on the board but the solutions I have seen are coming from the angle of knowing which column it is in first & then finding the last row from the bottom of the worksheet.
Workbooks("PS & Config - Actuals & FC.xlsm").Worksheets(2).Range("A3").CurrentRegion.Find(What:="FFA Name").Select
Range(ActiveCell, ActiveCell.End(xlDown)).Select
Range("A3").Select
ActiveSheet.Paste
To find the column use Match wit the column header name. Once you have that column, set the values in the destination range to be the same as that column. Selecting, copying, and pasting in VBA are unnecessary as the values themselves can be moved--plus it adds load.
I don't have Office anymore so I'm running this from memory. I hope it helps.
dim wb as workbook, ws1, ws2 as worksheet, myCol, myRow as long
set wb=excel.thisworkbook 'assuming this code goes in that workbook
set ws1=wb.sheets(2) 'set variables
myCol=worksheetfunction.match("FFA Name",ws1.[a1:zz1],0) 'search through 1st row
myRow=ws1.[a3].currentregion.rows.count 'grab last row containing data in this set
'do not select, nor copy and paste, if it can all be done with VBA. This can.
set ws2=wb.sheets.add 'a little rusty on this line, you can get the method from the macro recorder
ws2.cells(1,1).resize(myrow).value=ws1.cells(1,myCol).resize(myrow).value
The reason your original code stops when there's a blank cell is because the .end() method simulates pushing the end key and then an arrow, which goes to the first/last contiguous cell with data.
Range(ActiveCell, ActiveCell.End(xlDown)).Select

paste data into active cells

I write a very simple code
Sub copy_unibeton_muss()
Worksheets("source").Range("a8:c8").Copy
End Sub
The code will copy the range A8:C8. I added another portion to paste active cells in the active selected range.
Destination:=ActiveCell
But unfortunately the code paste only the data in the first row onlly. I need to paste data in all selected range may be 5x3 or 6x3 whatever I needed.
Use
Worksheets("source").Range("a8:c8").CopY Destination:= Selection
This will work as expected provided Selection has same number of columns of copied range

How to update cell references when moving cells into same sheet as target?

How do you force an excel workbook to use itself as a source for worksheet links?
I'm writing a VBA macro to automate the process of adding an excel worksheet into a workbook. The worksheet (sheet1) takes only certain (but very many) responses from within the several sheets (response1, response2, response3) of the questionnaire. As a result of this, sheet1 contains lots of cell references that don't lead anywhere until after the macro is run.
For instance a1 in sheet1 "='response1'!b6". This returns a #REF! error before the macro is run (which is fine).
After the macro is run sheet1 is now inside the correct workbook, and "='response1'!b6" is now a valid cell reference.
Except excel doesn't realise this until after I manually click the cell in Sheet1, press f2, then press enter. When I do this the cell is correctly populated. The trouble is there are large numbers of cells.
Is it possible to construct a VBA macro that will simulate this process of selecting formula boxes and pressing "Enter". Looking up people with similar problems, most have had the problem remedied by some combination of f9, turning automatic calculation back on, or ActiveSheet.Calculate or a variant. None of these have worked, it appears to be an issue with references, even though the references point to valid locations.
Otherwise, is it possible to use VBA to perform the same process as:
Data > Edit Links > Update Values
But in this case we'd need to specify the currently opened workbook as it's own source. Is there any way to do this?
When I manually selected the current workbook as the source under "Edit Links > Update Values" excel strangely repeats the worksheet name in the cell references, like this: "='[response1]response1!B31", which then fails to update when cell b31 changes, so this is not a solution.
Here's the code that runs on button press:
Private Sub CommandButton1_Click()
'copy worksheet into responses
Dim CopyFromWbk As Workbook
Dim CopyToWbk As Workbook
Dim CopyToWbk As Workbook
Set CopyFromWbk = Workbooks("Addition.xlsm")
Set ShToCopy = CopyFromWbk.Worksheets("Sheet1")
Set CopyToWbk = Workbooks("QuestionnaireResponses.xlsm")
ShToCopy.Copy After:=CopyToWbk.Sheets(CopyToWbk.Sheets.Count)
Workbooks("QuestionnaireResponses.xlsm").Activate
'Put code to update links in here
ThisWorkbook.UpdateLink Name:="myfilepathgoeshere.QuestionnaireResponses.xlsm", Type:=xlExcelLinks
'End update links
Thanks for any help, this one's a head scratcher.
Great idea from #Kyle. For those who having trouble forcing cell references to update, TextToColumns works.
However TextToColumns draws an error if the source range is empty, so if there's any chance of that being the case use an if statement with no action attached to skip over those instances.
My successful code looks like this:
Dim i As Integer
For i = 1 To 1004
'Scans through row 2 from col A onwards
'If cell is empty, does nothing.
'If cell is not empty, performs TextToColumns where source range = target range.
If IsEmpty(Workbooks("QuestionnaireResponses.xlsm").Worksheets_
("response1").Cells(2, i)) Then 'Does nothing if the cell is empty.
Else
Workbooks("QuestionnaireResponses.xlsm").Worksheets("response1").Cells(2, i).Select
Selection.TextToColumns Cells(2, i) 'Performs TextToColumns
End If
Next
All of my data is on the same long row. To apply the above to an entire spreadsheet, just nest everything between, and including, For i = 1 and Next within another For loop with different letter replacing i.

What is the difference between Sheets.Select and Sheets.Activate?

In VBA for Excel, what is the difference between Sheets.Select and Sheets.Activate ?
The difference is in their flexibility.
Activate make the specified sheet the active sheet, and may only be applied to a single sheet
Select allow for optionally extending the currently selected sheets to include the specified sheet, eg
Worksheets("Sheet2").Select Replace:=False
and also allow for selecting an array of sheets
Sheets(Array("Sheet3", "Sheet2")).Select
In their minimal form Select and Activate do the same thing.
For example, if only one sheet is currently selected (say Sheet3) or if more than one sheet is selected but excluding say Sheet2, then Worksheets("Sheet2").Select and Worksheets("Sheet2").Activate both make Sheet2 the sole selected and active sheet.
On the other hand, if say both Sheet2 and Sheet3 are selected and Sheet2 is the active sheet, then Worksheets("Sheet3").Activate leaves both sheets selected and makes Sheet3 the active sheet, whereas Worksheets("Sheet2").Select makes Sheet3 the sole selected and active sheet.
.activate is you clicking on the worksheet tab.
.select simulates you doing a control and click on the tab. In VBA you're not in the sheet yet.
You can .select more than one sheet but .activate only one.
To expand on the above: When the code below is run with Replace:=False no worksheet deactivation event occurs on sheet4. If Replace:=True is used instead then the de-activation event will fire.
Preventing the event is desirable in most circumstances as it can cause unexpected behaviour.
This means that select is only the equivalent of CTRL+Clicking a worksheet tab IF replace:=false is used.
sub a
Dim rng As Range
Sheet4.Select Replace:=False
Set rng = Selection
Sheet5.Select Replace:=True
Selection = rng.Value
end sub
Thanks for your posts as it helped me understand the difference.
Harvey

Resources