I'm not very advanced in this however I'm hoping to obtain some direction. I'm currently running the following VBA:
Private Sub CommandButton1_Click()
If (CheckBox1.Value = True) Then
ActiveSheet.Range("B13:E18").Copy
End If
If (CheckBox2.Value = True) Then
ActiveSheet.Range("B20:E25").Copy
End If
If (CheckBox3.Value = True) Then
ActiveSheet.Range("B27:E32").Copy
End If
If (CheckBox4.Value = True) Then
ActiveSheet.Range("B34:E39").Copy
End If
'copy the chunk above for more check boxes
End Sub
However, it only ends up copying the last selected checkbox instead of multiple cells at once. What am I missing in order to copy only selected cells per a checkbox and copying them over to another worksheet within the same workbook?
Here's a crude but working example:
Public Sub CommandButton1_Click()
Dim rgCopy As Range
With ActiveSheet
If CheckBox1 Then
Set rgCopy = .Range("B13:E18")
End If
If CheckBox2 Then
If rgCopy Is Nothing Then
Set rgCopy = .Range("B20:E25")
Else
Set rgCopy = Union(rgCopy, .Range("B20:E25"))
End If
End If
If CheckBox3 Then
If rgCopy Is Nothing Then
Set rgCopy = .Range("B27:E32")
Else
Set rgCopy = Union(rgCopy, .Range("B27:E32"))
End If
End If
If CheckBox4 Then
If rgCopy Is Nothing Then
Set rgCopy = .Range("B34:E39")
Else
Set rgCopy = Union(rgCopy, .Range("B34:E39"))
End If
End If
End With
If Not rgCopy Is Nothing Then
rgCopy.Copy
Else
MsgBox "nothing selected message"
End If
End Sub
Copy Ranges Depending on Checkboxes' Value
Standard Module e.g. Module1
Option Explicit
Sub CopyChkBoxConsecutiveRanges(ByVal chkBoxes As Variant)
' Source
Const sName As String = "Sheet1"
Const sfrgAddress As String = "B13:E18"
Const sGap As Long = 1
' Destination
Const dName As String = "Sheet2"
Const dfCellAddress As String = "A2"
' Workbook
Dim wb As Workbook: Set wb = ThisWorkbook
' Source
Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
Dim srg As Range: Set srg = RefChkBoxConsecutiveRanges( _
sws.Range(sfrgAddress), chkBoxes, sGap)
'Destination
Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
Dim dfCell As Range: Set dfCell = dws.Range(dfCellAddress)
' Copy
If Not srg Is Nothing Then
srg.Copy dfCell
End If
End Sub
Function RefChkBoxConsecutiveRanges( _
ByVal sfrg As Range, _
ByVal chkBoxes As Variant, _
Optional ByVal sGap As Long = 0, _
Optional ByVal SearchOrder As XlSearchOrder = xlByRows) _
As Range
' Needs `RefCombinedRange`.
Dim sws As Worksheet: Set sws = sfrg.Worksheet
Dim srOffset As Long
srOffset = IIf(SearchOrder = xlByRows, sfrg.Rows.Count + sGap, 0)
Dim scOffset As Long
scOffset = IIf(SearchOrder = xlByRows, 0, sfrg.Columns.Count + sGap)
Dim scrg As Range: Set scrg = sfrg
Dim srg As Range
Dim n As Long
For n = LBound(chkBoxes) To UBound(chkBoxes)
If chkBoxes(n) Then
Set srg = RefCombinedRange(srg, scrg)
End If
Set scrg = scrg.Offset(srOffset, scOffset)
Next n
If Not srg Is Nothing Then
Set RefChkBoxConsecutiveRanges = srg
End If
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Creates a reference to a range combined from two ranges.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefCombinedRange( _
ByVal CombinedRange As Range, _
ByVal AddRange As Range) _
As Range
If CombinedRange Is Nothing Then
Set RefCombinedRange = AddRange
Else
Set RefCombinedRange = Union(CombinedRange, AddRange)
End If
End Function
Userform Module e.g. UserForm1
Private Sub CommandButton1_Click()
Dim chkBoxes As Variant
chkBoxes = Array(CheckBox1, CheckBox2, CheckBox3, CheckBox4) ' add more
CopyChkBoxConsecutiveRanges chkBoxes
End Sub
Related
Sub all_col()
Workbooks("xlsb file").Worksheets("sheet name").Range("A1:CR1048576").Copy_
Workbooks("xlsx file").Worksheets("sheet name").Range("A1")
How do I write more efficient code to copy all the cell ranges from one worksheet to another within different workbooks.instead of using "A1:CR1048576" is there a better way?
Try using the UsedRange property of the worksheet.
Sub all_col()
wb1.Worksheets("sheet name").UsedRange.Copy _
wb2.Worksheets("sheet name").Range("A1")
End Sub
Copy Worksheet In Closed Workbook to Worksheet in ThisWorkbook
The function is a sub converted to a function to return a boolean indicating whether it was successful i.e. whether no errors occurred.
You could classify this code as an 'import operation': the source workbook is closed, while the destination workbook contains the code. With 'a few changes', you could rewrite this code as an 'export operation': the destination workbook is closed and the source workbook contains the code. Looking at the file extensions, it looks like you needed the latter.
Option Explicit
Sub WsToWsInThisWorkbookTEST()
Dim GotCopied As Boolean: GotCopied = WsToWsInThisWorkbook( _
"C:\Test\Test.xlsx", "Sheet1", "A1", "Sheet1", "A1")
If Not GotCopied Then Exit Sub
'Continue with your code e.g.:
MsgBox "Worksheet got copied.", vbInformation
End Sub
Function WsToWsInThisWorkbook( _
ByVal SourceFilePath As String, _
Optional ByVal SourceSheetID As Variant, _
Optional ByVal SourceFirstCell As String = "A1", _
Optional ByVal DestinationSheetID As Variant = "Sheet1", _
Optional ByVal DestinationFirstCell As String = "A1") _
As Boolean
On Error GoTo ClearError
Const ProcName As String = "WsToWsInThisWorkbook"
' Source
If Len(Dir(SourceFilePath)) = 0 Then
MsgBox "Source file '" & SourceFilePath & "' not found.", vbCritical
Exit Function
End If
Dim swb As Workbook: Set swb = Workbooks.Open(SourceFilePath, True, True)
Dim sws As Worksheet: Set sws = swb.Sheets(SourceSheetID)
Dim srg As Range
With sws.UsedRange
Dim lcell As Range: Set lcell = .Cells(.Rows.Count, .Columns.Count)
Set srg = sws.Range(SourceFirstCell, lcell)
End With
' Destination.
Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
Dim dws As Worksheet: Set dws = dwb.Sheets(DestinationSheetID)
Dim dfCell As Range: Set dfCell = dws.Range(DestinationFirstCell)
' Copy.
srg.Copy dfCell
WsToWsInThisWorkbook = True
ProcExit:
On Error Resume Next
If Not swb Is Nothing Then swb.Close SaveChanges:=False
On Error GoTo 0
Exit Function
ClearError:
MsgBox "Run-time error '" & Err.Number & "':" & vbLf & Err.Description, _
vbCritical, ProcName
Resume ProcExit
End Function
Most of the answers provided would work but UsedRange extends to formatting (see this epic thread] discussing best method to find last row).
If that were an issue, you could include these functions below your original macro and it will be the precise space to copy from:
Sub all_col()
Dim lastRow As Long, lastColumn As Long
With Workbooks("xlsb file").Worksheets("sheet name")
lastRow = FindLastRowInSheet(.Range("A1"))
lastColumn = FindLastColumnInSheet(.Range("A1"))
.Range("A1").Resize(lastRow, lastColumn).Copy_
Workbooks("xlsx file").Worksheets("sheet name").Range ("A1")
End With
End Sub
Function FindLastRowInRange(someColumns As Range) As Long
Const zFx = "=MAX(FILTER(ROW(????),NOT(ISBLANK(????)),0))"
Dim tRng As Range, i As Long, tRow As Long, pRng As Range
With someColumns.Worksheet
Set tRng = Intersect(someColumns.EntireColumn, .UsedRange)
For i = 1 To tRng.Columns.Count
Set pRng = Intersect(tRng.Columns(i), _
Range(.Rows(FindLastRowInRange + 1), .Rows(.Rows.Count)))
If Not pRng Is Nothing Then
tRow = .Evaluate(Replace(zFx, "????", _
pRng.Address, 1, -1))
If tRow > FindLastRowInRange Then _
FindLastRowInRange = tRow
End If
Next i
End With
End Function
Function FindLastRowInSheet(anywhereInSheet As Range) As Long
FindLastRowInSheet = FindLastRowInRange(anywhereInSheet.Worksheet.UsedRange)
End Function
Function findLastColumn(someRows As Range) As Long
Const zFx = "=MAX(FILTER(COLUMN(????),NOT(ISBLANK(????)),0))"
Dim tRng As Range, i As Long, tRow As Long, pRng As Range
With someRows.Worksheet
Set tRng = Intersect(.UsedRange, someRows.EntireRow)
For i = 1 To tRng.Rows.Count
Set pRng = Intersect(tRng.Rows(i), Range(.Rows(.Columns.Count), .Rows(findLastColumn + 1)))
If Not pRng Is Nothing Then
tRow = .Evaluate(Replace(zFx, "????", _
pRng.Address, 1, -1))
If tRow > findLastColumn Then _
findLastColumn = tRow
End If
Next i
End With
End Function
Function FindLastColumnInSheet(anywhereInSheet As Range) As Long
FindLastColumnInSheet = findLastColumn(anywhereInSheet.Worksheet.UsedRange)
End Function
How do you create a range in code and using those name ranges to find the average and then displaying that value into a certain cell
I am trying my hardest!!
My Code:
Sub NameRanges()
Dim HourlyConsumption As Range
Set HourlyConsumption = Range("B2:B251")
ThisWorkbook.Names.Add name:="HourlyConsumption", RefersTo:=HourlyConsumption
Dim Replenishment As Range
Set Replenishment = Range("C2:C251")
ThisWorkbook.Names.Add name:="Replenishment", RefersTo:=Replenishment
End Sub
Sub DataAverages()
Dim AVGHourlyConsumption As Double
Dim AVGReplenishment
AVGHourlyConsumption = (Range("HourlyConsumption").Value) / ("HourlyConsumption")
AVGReplenishment = (Range("Replenishment").Value) / ("Replenishment")
Set AVGHourlyConsumption.Value = Cells("H1")
Set AVGReplenishment.Vaule = Cells("H2")
End Sub
Add Named Range
Option Explicit
Sub DoTheJob() ' rename appropriately!
NameRanges
PopulateAverages
End Sub
Sub NameRanges()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim sws As Worksheet: Set sws = wb.Worksheets("Sheet1") ' adjust!
' Use the 'AddNamedRange' method to safely add the named ranges:
AddNamedRange "HourlyConsumption", "B2:B251", sws
AddNamedRange "Replenishment", "C2:C251", sws
End Sub
Sub PopulateAverages()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Note that this worksheet can be different
' than the worksheet containing the named ranges.
Dim dws As Worksheet: Set dws = wb.Worksheets("Sheet1") ' adjust!
' Formulas
With dws.Range("H1")
.Formula = "=IFERROR(AVERAGE(HourlyConsumption),"""")"
'.NumberFormat = "0.0000"
'.Font.Bold = True
'.Interior.Color = vbYellow
End With
With dws.Range("H2")
.Formula = "=IFERROR(AVERAGE(Replenishment),"""")"
'.NumberFormat = "0.0000"
'.Font.Bold = True
'.Interior.Color = vbYellow
End With
' Values
' With dws.Range("H1")
' .Value = dws.Evaluate("IFERROR(AVERAGE(HourlyConsumption),"""")")
' End With
' With dws.Range("H2")
' .Value = dws.Evaluate("IFERROR(AVERAGE(Replenishment),"""")")
' End With
End Sub
Sub AddNamedRange( _
ByVal RangeName As String, _
ByVal RangeAddress As String, _
ByVal WorksheetObject As Worksheet, _
Optional ByVal ApplyWorksheetScope As Boolean = False)
With WorksheetObject
On Error Resume Next
.Parent.Names(RangeName).Delete
On Error GoTo 0
If ApplyWorksheetScope Then
.Names.Add RangeName, .Range(RangeAddress)
Else
.Parent.Names.Add RangeName, .Range(RangeAddress)
End If
End With
End Sub
I have a spreadsheet with over 10000 rows. I need to search it using InputBox (UPC field, input is from a barcode scanner).
I need to copy the row of the found cell, and paste it to another sheet.
This process should loop until the user cancels the InputBox.
I have done this, but it gives me an error on the SelectCells.Select line, but not every time.
Sub Scan()
Do Until IsEmpty(ActiveCell)
Dim Barcode As Double
Barcode = InputBox("Scan Barcode")
Dim ws As Worksheet
Dim SelectCells As Range
Dim xcell As Object
Set ws = Worksheets("Sheet1")
For Each xcell In ws.UsedRange.Cells
If xcell.Value = Barcode Then
If SelectCells Is Nothing Then
Set SelectCells = Range(xcell.Address)
Else
Set SelectCells = Union(SelectCells, Range(xcell.Address))
End If
End If
Next
SelectCells.Select
Set SelectCells = Nothing
ActiveCell.Rows("1:1").EntireRow.Select
Selection.Copy
Sheets("Sheet2").Select
ActiveSheet.Paste
Sheets("Sheet1").Select
Loop
End Sub
Copy Rows
Option Explicit
Sub Scan()
Const sName As String = "Sheet1"
Const Header As String = "Barcode"
Const dName As String = "Sheet2"
Const dFirstCellAddress As String = "A2"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
Dim surg As Range: Set surg = sws.UsedRange
Dim slCell As Range
Set slCell = surg.Cells(surg.Rows.Count, surg.Columns.Count)
Dim shCell As Range
Set shCell = surg.Find(Header, slCell, xlFormulas, xlWhole, xlByRows)
If shCell Is Nothing Then
MsgBox "The cell containing the header '" & Header _
& "' was not found.", vbCritical
Exit Sub
End If
Dim sfCol As Long: sfCol = surg.Column
Dim srg As Range
Set srg = sws.Range(sws.Cells(shCell.Row + 1, sfCol), slCell)
Dim scColIndex As Long: scColIndex = shCell.Column - sfCol + 1
Dim scrg As Range: Set scrg = srg.Columns(scColIndex)
Dim SelectedRows As Range
Dim Barcode As Variant
Dim srIndex As Variant
Do
Barcode = InputBox("Scan Barcode")
If Len(CStr(Barcode)) = 0 Then Exit Do
If IsNumeric(Barcode) Then
srIndex = Application.Match(CDbl(Barcode), scrg, 0)
If IsNumeric(srIndex) Then
If SelectedRows Is Nothing Then
Set SelectedRows = srg.Rows(srIndex)
Else
Set SelectedRows = Union(SelectedRows, srg.Rows(srIndex))
End If
End If
End If
Loop
If SelectedRows Is Nothing Then
MsgBox "No scan results.", vbExclamation
Exit Sub
End If
Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
Dim dfCell As Range: Set dfCell = dws.Range(dFirstCellAddress)
Dim durg As Range: Set durg = dws.UsedRange
Dim dlRow As Long: dlRow = durg.Row + durg.Rows.Count - 1
Dim dlCell As Range
If dlRow < dfCell.Row Then
Set dlCell = dfCell
Else
Set dlCell = dws.Cells(dlRow + 1, dfCell.Column)
End If
SelectedRows.Copy dlCell
MsgBox "Rows copied.", vbInformation
End Sub
You can try something like this:
Sub Scan()
Dim Barcode As String, rngData As Range, m, rngDest As Range
'Column with barcodes
With Worksheets("Sheet1")
Set rngData = .Range("D1", .Cells(Rows.Count, "D").End(xlUp))
End With
'First paste postion
Set rngDest = Worksheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Offset(1)
Do
Barcode = InputBox("Scan Barcode")
If Len(Barcode) = 0 Then Exit Do
'm = Application.Match(Barcode, rngData, 0) 'Barcodes formatted as text
m = Application.Match(CDbl(Barcode), rngData, 0) 'Barcodes formatted as numbers
If Not IsError(m) Then
rngData.Rows(m).EntireRow.Copy rngDest 'copy to Sheet2
Set rngDest = rngDest.Offset(1)
Else
'if no match then what?
Debug.Print "no match"
End If
Loop
End Sub
Depending on how your barcodes are stored (as text, or a numeric values) you may need to use CDbl(Barcode) inside the call to Match()
Im trying to create a function in VBA that copies data from one sheet to another based on the input to the function. However, I'm having great difficulty in using the arguments to the function in the actual function itself.
Below is my code: as you can see, the range I want is hardcoded in for now, and this works! But I cannot get it to accept the range I pass as an argument to the function. What am I doing wrong?
data should be in place of range(F35:F65) and target should be in place of range(C6)
Function Copytranspose(data As Range, target As Range)
Worksheets("Data").Activate
ActiveSheet.Range("F35:F65").Copy
Worksheets("Totalizers").Activate
ActiveSheet.Range("C6").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Function
Sub tempo()
Call Copytranspose(Range("F35:F65"), Range("C6"))
End Sub
Copy Values of a Range
Two HardCoded Worksheets (Range Address (String) Parameters)
Option Explicit
Sub CopyRange( _
ByVal SourceRangeAddress As String, _
ByVal DestinationFirstCellAddress As String, _
Optional ByVal DoTranspose As Boolean = False)
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim sws As Worksheet: Set sws = wb.Worksheets("Data")
Dim srg As Range: Set srg = sws.Range(SourceRangeAddress)
Dim dws As Worksheet: Set dws = wb.Worksheets("Totalizers")
Dim dfCell As Range: Set dfCell = dws.Range(DestinationFirstCellAddress)
Dim drg As Range
If DoTranspose Then
Set drg = dfCell.Resize(srg.Columns.Count, srg.Rows.Count)
drg.Value = Application.Transpose(srg.Value)
Else
Set drg = dfCell.Resize(srg.Rows.Count, srg.Columns.Count)
drg.Value = srg.Value
End If
End Sub
Sub tempo()
' Either transpose...
CopyRange "F35:F65", "C6", True ' 'C6:AG6'
' ... or do not transpose:
'CopyRange "F35:F65", "C6" ' 'C6:C36'
End Sub
Any Ranges (Range Parameters)
Option Explicit
Sub CopyRange( _
ByVal srg As Range, _
ByVal dfCell As Range, _
Optional ByVal DoTranspose As Boolean = False)
Dim drg As Range
If DoTranspose Then
Set drg = dfCell.Resize(srg.Columns.Count, srg.Rows.Count)
drg.Value = Application.Transpose(srg.Value)
Else
Set drg = dfCell.Resize(srg.Rows.Count, srg.Columns.Count)
drg.Value = srg.Value
End If
End Sub
Sub tempo()
' Either transpose...
CopyRange Range("F35:F65"), Range("C6"), True ' 'C6:AG6'
' ... or do not transpose:
'CopyRange Range("F35:F65"), Range("C6") ' 'C6:C36'
End Sub
Something like this?
Sub CopyData(sourceRange As Excel.Range, targetRange As Excel.Range)
targetRange.Resize(sourceRange.Rows.Count, sourceRange.Columns.Count).Value = sourceRange.Value
End Sub
Sub TestCopyData()
CopyData Sheets("Sheet1").Range("a1:a3"), Sheets("sheet1").Range("q1")
End Sub
So I want to copy lets say Rows 5-15 from Columns B,E,G, from one worksheet to another.
So far I have tried it like this
Sheets("Table1").Select
Range("B5:B15,E5:E15,G5:G15").Select
Selection.Copy
Sheets("Table2").Select
Range("B4").Select
ActiveSheet.Paste
That's the concept.
I have much more Columns to copy and when doing it it doesn't work as I want like this
Sheets("Table1").Select
Range("CT5:CT15,CB5:CB15,CN5:CN15,DJ5:DJ15,DL5:DL15,E5:E15,AP5:AP15,CU5:CU15,AZ5:AZ15,AX5:AX15,CZ5:CZ15,CV5:CV15,AR5:AR15,AM5:AM15,Q5:Q15,CG5:CG15,AC5:AC15,R5:R15,CY5:CY15,G5:G15,Z5:Z15,C5:C15,DP5:DP15,Y5:Y15,X5:X15,CJ5:CJ15,DQ5:DQ15,CQ5:CQ15,AK5:AK15,AJ5:AJ15,BA5:BA15,BQ5:BQ15,CL5:CL15,BH5:BH15,DO5:DO15,AB5:AB15,CH5:CH15,CK5:CK15,P5:P15,CI5:CI15").Select
Selection.Copy
Sheets("Table2").Select
Range("B4").Select
ActiveSheet.Paste
Is there a way to streamline? To say I wand Row 5-15 from all these columns?
Thank you
You could use Intersect to get the range to copy.
Dim rngCopy As Range
Dim rngCols As Range
Dim rngRows As Range
With Sheets("Tabelle1")
Set rngCols = .Range("B:B, E:E, G:G")
Set rngRows = .Rows("5:15")
End With
Set rngCopy = Intersect(rngCols, rngRows)
rngCopy.Copy Sheets("Tabelle2").Range("A4")
Copy Non-Contiguous Columns Range
Adjust the values in the constants section.
Option Explicit
Sub copyMultiColumns()
' Source
Const sName As String = "Table1"
Const sRows As String = "5:15"
Const sColsList As String = "" _
& "C,E,G,P,Q,R,X,Y,Z," _
& "AB,AC,AJ,AK,AM,AP,AR,AX,AZ," _
& "BA,BH,BQ," _
& "CB,CG,CH,CI,CJ,CK,CL,CN,CQ,CT,CU,CV,CY,CZ," _
& "DJ,DL,DO,DP,DQ"
' Destination
Const dName As String = "Table2"
Const dFirst As String = "B4"
' Workbook
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Source
Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
Dim sCols() As String: sCols = Split(sColsList, ",")
Dim srg As Range
Dim n As Long
For n = 0 To UBound(sCols)
If srg Is Nothing Then
Set srg = sws.Columns(sCols(n))
Else
Set srg = Union(srg, sws.Columns(sCols(n)))
End If
Next n
Set srg = Intersect(srg, sws.Rows(sRows))
' Destination
Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
srg.Copy dws.Range(dFirst)
End Sub