Using the CurrentRegion property in VBA - vba

I want to write a simple VBA macro to copy the data in a range that corresponds to the block of cells around an active cell in Sheet1 and Paste it in Sheet2. (preferably in the same address as of in Sheet1).
The code I have written is:
Option Explicit
Dim Cello As Range
Sub CopyCurrentRegion2()
Set Cello = Worksheets("Sheet1").Range(ActiveCell.Address)
Cello.CurrentRegion.Copy Sheets("Sheet2").Range(Cello)
End Sub
Please correct this prog. It is giving run time error: 1004.

Consider:
Sub CopyStuff()
With ActiveCell.CurrentRegion
.Copy Sheets("Sheet2").Range(.Address)
End With
End Sub

Related

how to dynamically update a workbook name in excel using vba?

I’m trying to dynamically update a workbook name in a formula in excel to bring through data from a continually changing source file.
So far I have been getting by with using an indirect formula, but now I have a huge workbook with around 216,000 cells to populate and I don’t think indirect is the most efficient way to do this.
I want to use VBA instead but I have no experience with this. From doing some googling I have found a few things but I’m not sure how to implement my specific needs into the code.
so far 've come up with this:
Sub replace()
Dim cell As Range
cell.Formula = replace(cell.Formula, "OfficeSupplies.csv",
"OfficeSupplies2.csv")
Range("a1:d8").Value
Next
End Sub
However, when I try to execute it, it doesn't work at all.
Edited to insert the handling of a specified range instead of ActiveSheet used range and to handle a sheet different to "Active" one
To answer the question, you could use a code like the following to replace in "Active" sheet used range:
Sub replace()
ActiveSheet.UsedRange.SpecialCells(xlCellTypeFormulas).Replace(What:="OfficeSupplies.csv", Replacement:="OfficeSupplies2.csv", LookAt:=xlPart)
End Sub
or you could explicitly refer to a sheet:
Sub replaceInSpecifiedSheet()
Worksheets("MySheetName").UsedRange.SpecialCells(xlCellTypeFormulas).Replace(What:="OfficeSupplies.csv", Replacement:="OfficeSupplies2.csv", LookAt:=xlPart) ' change "MySheetName" to your actual sheet name
End Sub
or you could want to change formulas in a given range:
Sub replaceInSpecifiedRangeOfSpecifiedSheet()
Worksheets("MySheetName").Range("A5:B8").SpecialCells(xlCellTypeFormulas).Replace(What:="OfficeSupplies.csv", Replacement:="OfficeSupplies2.csv", LookAt:=xlPart) ' change "MySheetName" to your actual sheet name
End Sub
But changing a formula in 216k cells can be quite a time consuming activity
You may consider the opposite: change the name of the”continually changing source file”
You can do that without VBA of course
Should you be “forced” to or prefer use VBA then you could use ‘Name ... As‘ statement
Sub replace2()
Dim FullNameToChange As String
Dim HardCodedFullName As String
FullNameToChange = "C:\ChangingName.xls"
HardCodedFullName = "C:\HardCodedName.xls"
If Dir(FullNameToChange) <> "" And Dir(HardCodedFullName) = "" Then Name FullNameToChange As HardCodedFullName
End Sub
Give this a try
Cells.Replace "OfficeSupplies.csv", "OfficeSupplies2.csv", xlPart, , True

Copy Row A1 from Sheet 1 into Row A1 Sheet 2

I basically just need to know how to copy a header from sheet one that goes from A1-O1 into sheet two, three, four, five and so on...they all have the same header. Sheet one is on the right and sheet two is left and increases to the left. I tried this which I found on some website but it says object required. The error is Runtime Error 424
mainworkBook.Sheets(“Sheet1”).Rows(1).EntireRow.Copy
mainworkBook.Sheets(“Sheet2”).Range(“A1”).Select
mainworkBook.Sheets(“Sheet2”).Paste
A small loop code.let me know if it works.
Sub COPYPASTeHEADER()
Dim K As Integer
For K = 2 To ActiveWorkbook.Sheets.Count
Sheets("All_Data").Range("A1:O1").COPY Sheets(K).Range("A1")
Next
End Sub
You can do something like this instead of using Select:
For Each Sheet In ThisWorkbook.Sheets
ThisWorkbook.Sheets("ALL_DATA").Rows(1).Copy Destination:=Worksheets(Sheet.Name).Range("A1")
Next
This will loop through each sheet in your workbook, take the range you provided (row 1 from Sheet1), and paste it to each sheet by referencing the Name property of each Sheet you are looping through.
The error may have been from the workbook variable, as that is the only thing that is unclear.
I would also recommend looking into this post: How to avoid using Select in Excel VBA macros as it is tremendously helpful in avoiding Select/Activate when possible, which is a common occurrence among those who learn VBA through recording Macros.
Let me know if it works for you.
This is an excellent place to use a loop. For each sheet in the workbook, paste the same header.
Sub forEachWs()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Call pasteContents(ws)
Next
End Sub
Sub pasteContents(ws as Worksheet)
** Your code goes here
End Sub
EDIT: The ** section could be as such:
Sub pasteContents(ws as Worksheet)
ActiveWorkbook.Sheets(“Sheet1”).Rows(1).EntireRow.Copy
ActiveWorkbook.Sheets(ws).Range(“A1”).Select
ActiveWorkbook.Sheets(ws).Paste
End Sub
Or it could also be...
Sub pasteContents(ws as Worksheet)
ActiveWorkbook.Sheets("Sheet1").Rows(1).Copy Destination:=Worksheets(ws).Range("A1")
End Sub

Excel vba if the statements and auto update

im looking for some basic help with VBA. I have created a userform for fellow members to fill out information when we go on a call. When ok is pressed, the data is sent to sheet2 and laid in the next open row. In sheet 3 i have the printable form of the userform that i made out. I am trying to write the vba code in the printable form, so when the call # changes in cell b2, it will automatically change all other cells in that form, with the corresponding data in the same row from sheet 2.
Im new to the forum so im not sure how to upload etc. but i will try and give an example below.
Sheet2 looks something like this, for the example each cell seperated by "."
18-170001.01/02/17.Accident."current address"."call info"
18-170002.01/02/17.Training."current address"."call info"
in sheet4 this is the code i am using and it is not working
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Long
For i = 5 To Row.Count
If sheet4 .cells(b2).value=sheet2.Cells(i,1).value then
sheet4.cells(e2).value=sheet2.cells(i,1).value
End If
Next i
End Sub
I would add additional if then statments for each cell in sheet 4 to match each cell in sheet 2.
Please any help is appreciated
You can't use Cells(b2), it needs to be Range("B2") or Cells(2, "B") or Cells(2, 2).
So your code could be:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Long
For i = 5 To Row.Count
If sheet4.cells(2, "B").value=sheet2.Cells(i,1).value then
sheet4.cells(2, "E").value=sheet2.cells(i,1).value
End If
Next i
End Sub
But you would be better off just using a formula for this purpose instead. For example, the above code could be replaced by having the following formula in cell E2 of sheet4:
=VLOOKUP(B2,Sheet2!A:A,1,FALSE)
(That assumes that sheet2 has a sheet name of "Sheet2".)

Copy and paste values and not formulas

Writing macro for the first time, I have to copy only cell values to another and which I got it working, however, I am not sure, how to copy entire column without specifying range since range may be different every time. Here, I am trying with a range which is working, but I want it to check values of cell for that column and until it finds a value copy/paste to the another column.
Here is the code I have so far:
Sub CopyingCellValues()
Range("E2:E7").Copy
Range("C2:C7").PasteSpecial xlPasteValues
End Sub
Thanks.
Simple Columns copy will be...
Sheets("Sheet Name").Columns(1).Copy Destination:=Sheets("Sheet Name").Columns(2)
Helpful info at MSDN on Getting Started with VBA in Excel 2010
Edit:
With out the formula, Try
Sub CopyingCellValues()
Range("E:E").Value = _
Range("C:C").Value
End Sub
Sub ValueToValue()
[E:E].Value = [C:C].Value
End Sub

Automate a macro based on a change within a range from another sheet

I am trying to automate a macro to run on sheet2 whenever a cell within a range on sheet1 is changed. I have tried a bunch of things and I don't have the vba experience to know what is wrong with them. Basically, sheet1 has my input, and I assigned a level of priority 1-5 to each item. Sheet2 shows only those items ranked 1, 3, or 4. I did this with if statements, but this leaves a bunch of blank rows in my table, so I can sort the blank rows out using the filter function. If I change a ranking on sheet1, I want my sheet2 table to automatically update. I wrote a sort function which resorts my sheet2 data appropriately but I am struggling to automate it so that it updates automatically when anything from sheet1 is changed. So far I have been using worksheet_change and can get sheet1 to refilter when sheet1 is changed, which is not what I want. Any ideas?
This is my current sort function:
Sub ReSort()
With Worksheets("Sheet2")
.Range("$A$2:$D$34").AutoFilter Field:=2
.Range("$A$2:$D$34").AutoFilter Field:=2, Criteria1:="<>"
End With
End Sub
This:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A:A")) Is Nothing Then
' Do something
End If
End Sub
Should do the trick
I finally got it to work! For those reading this and having a similar problem, I have this code saved in sheet1:
Sub ReSort()
'This function filters my table spanning A2:D34 by the second column and sorts out the blanks
With Worksheets("Sheet2")
.Range("$A$2:$D$34").AutoFilter Field:=2
.Range("$A$2:$D$34").AutoFilter Field:=2, Criteria1:="<>"
End With
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
'This function runs my ReSort function if any cell on sheet1 in E3:E34 or G3:G34 is changed
If Not Intersect(Target, Range("$E$3:$E$34,$G$3:$G$34")) Is Nothing Then
ReSort
End If
End Sub
Thanks to everyone for their help! I was seriously pulling my hair out in frustration with this.
Sounds like you're on the right path, worksheet_change is the correct way to go with this as you do want the macro to run when sheet1 is changed so you need to detect that.
I suspect you're just missing one thing, the macro that runs on sheet2, put it in a module reference sheet2 explicitly
For example,
Worksheets("Sheet1").Range("A1")
instead of just
Range("A1")
Then you can call the function to run from any sheet just by using the function name
If you need more detail, post all of the code you have so far and I will happily modify it to suit