Help needed. I'm a newbie to VBA and trying to start with simple macro.
But even with that failing miserably.
All i'm trying to do is copy and paste from one worksheet to another using an input box to specify the range to be copied.
Now I know for the input box is:
Application.InputBox("Enter the range from which you want to copy : ", Type:=8)
But what do line do i need in order to copy to a cell in another worksheet?
I apologise in advance for being an idiot.
Is this what you are trying?
Option Explicit
Sub Sample()
Dim rngCopyFrom As Range
On Error Resume Next
Set rngCopyFrom = Application.InputBox("Enter the range from which you want to copy", Type:=8)
On Error GoTo 0
If Not rngCopyFrom Is Nothing Then
'~~> Copy the range to say Cell A1 of Sheets("weekly raw")
rngCopyFrom.Copy ThisWorkbook.Sheets("weekly raw").Range("A1")
End If
End Sub
One way to do it is like this:
Sub CopyRange()
Dim FromRange As Range
Dim ToRange As Range
Set FromRange = Application.InputBox("Enter the range from which you want to copy : ", Type:=8)
Set ToRange = Application.InputBox("Enter the range to where you want to copy : ", Type:=8)
FromRange.Copy ToRange
'Or you can do it like this if you need some flexibility on Paste
'FromRange.Copy
'ToRange.PasteSpecial xlPasteValues, xlPasteSpecialOperationNone
End Sub
Here's some sample code:
Option Explicit
Sub CopyStuff()
Dim x As Range
Dim y As Range
Set x = Application.InputBox("Select what copy using the mouse", Type:=8)
Set y = ActiveWorkbook.Sheets("Sheet2").Range("A1")
x.Copy y
End Sub
Related
I would need to open a random selected link from a cell to a website in my list. My internet links are put in column B, but I cannot get it to open the hyperlink after it has selected a cell from my list.
Sub Test()
Dim Sh As Worksheet
Dim Rng As Range
Dim Cell As Range
Set Sh = Worksheets("Sheet1")
With Sh
Set Rng = .Range("C1:C" & .Cells(.Rows.Count, "C").End(xlUp).Row)
End With
For Each Cell In Rng
ThisWorkbook.FollowHyperlink Cell.Value
Next Cell
End Sub
Just to be sure I got it right:
The addresses are stored in column B (in your code you're using column C)
You don't want to open all of the addresses, but only one random one?
The addresses are full URLs? (Like "https://stackoverflow.com/")
I tidied up your code a little bit. Read the comments, to understand what is happening.
Sub Test()
Dim Sh As Worksheet
Dim Rng As Range
Dim Cell As Range
Set Sh = Worksheets(1)
' Get a Range object of all possible addresses
Set Rng = Intersect(Sh.UsedRange, Sh.Range("B:B"))
' Open one random element of them
ThisWorkbook.FollowHyperlink Rng(Int(Rnd * Rng.Count) + 1)
End Sub
---Update---
Thanks for the responses, I have found that DragonSamu's updated answer works perfectly.
---Original Post---
I have been trying to figure out where I am going wrong for the past few hours but I can't spot it. I think it's because the script is trying to draw the value from the active worksheet which is not what I want. Hopefully somebody can put me on the rite track - I think the answer should be relatively obvious but I just can't see it!
Basically, I am trying to populate a Combobox with a dynamic range of values that exist in another worksheet (but in the same workbook). I can get the Combobox to populate when I run the script in the worksheet 'Materials' (which is where the dynamic list is drawn from) but not when I run it in the worksheet 'Products'.
Unfortunately the script is designed to populate Products with Materials so is be run in a UserForm when the 'Products' worksheet is open and the 'Materials' worksheet would therefore be inactive.
I should also note that this script has been adapted from code I found elsewhere on this forum, so if it seems familiar I thank you in advance :)
Private Sub UserForm_Initialize()
Dim rRange As Range
On Error GoTo ErrorHandle
'We set our range = the cell B7 in Materials
Set rRange = Worksheets("Materials").Range("B7")
'Check if the cell is empty
If Len(rRange.Formula) = 0 Then
MsgBox "The list is empty"
GoTo BeforeExit
End If
'Finds the next empty row and expands rRange
If Len(rRange.Offset(1, 0).Formula) > 0 Then
Set rRange = Range(rRange, rRange.End(xlDown))
End If
'The range's address is our rowsource
Mat1_Name_ComBox.RowSource = rRange.Address
Mat2_Name_ComBox.RowSource = rRange.Address
Mat3_Name_ComBox.RowSource = rRange.Address
Mat4_Name_ComBox.RowSource = rRange.Address
Mat5_Name_ComBox.RowSource = rRange.Address
BeforeExit:
Set rRange = Nothing
Exit Sub
ErrorHandle:
MsgBox Err.Description
Resume BeforeExit
End Sub
Any help is much appreciated.
Cheers,
Simon
From what I can see your code would be giving an error here:
If Len(rRange.Offset(1, 0).Formula) > 0 Then
Set rRange = Range(rRange, rRange.End(xlDown))
End If
Because your trying to set rRange by using Range() without defining the Worksheet first. This will get the Range from the ActiveWorksheet.
change it to the following:
If Len(rRange.Offset(1, 0).Formula) > 0 Then
Set rRange = Worksheets("Materials").Range(rRange, rRange.End(xlDown))
End If
best practice would be the following:
Private Sub UserForm_Initialize()
Dim wb as Workbook
Dim sh as Worksheet
Dim rRange As Range
On Error GoTo ErrorHandle
'Set the Workbook and Worksheet
set wb = Workbooks("products.xlsx")
set sh = wb.Worksheets("Materials")
'We set our range = the cell B7 in Materials
Set rRange = sh.Range("B7")
'Check if the cell is empty
If Len(rRange.Formula) = 0 Then
MsgBox "The list is empty"
GoTo BeforeExit
End If
'Finds the next empty row and expands rRange
If Len(rRange.Offset(1, 0).Formula) > 0 Then
Set rRange = sh.Range(rRange, rRange.End(xlDown))
End If
By properly defining and setting your Workbook and Worksheet you correctly reference to them and don't get errors.
Update:
the 2nd problem is that rRange.Address only places the Range location inside your .RowSource not the Sheet it needs to look at.
change:
Mat1_Name_ComBox.RowSource = rRange.Address
to:
dim strSheet as String
strSheet = "Materials"
Mat1_Name_ComBox.RowSource = strSheet + "!" + rRange.Address
This way it will include the Sheet name into the .RowSource
I have been trying to copy and paste from one sheet to another, whereby the cells should be copied with the pastelink feature, while making use of the input box to let the user enter the range where he wants to paste the copied data. The code works within the same sheet but not on a different one. Even if it works, it does not recognise the range I have entered in the input box. Instead, it recognises the cursor and pastes whereby the cursor is in the destination worksheet.
This is the code I used for the copying and pasting from sheet 1 to sheet 2. Is there any problem with the codes for which why it does not recognise the range I have entered in the input box?
Sub tryuserinput()
Dim rng As Range
Dim inp As Range
Selection.Interior.ColorIndex = 37
Set inp = Selection
Set rng = Application.InputBox("Copy to", Type:=8)
inp.Copy
rng.Select
Worksheets("Sheet2").Paste Link:=True
End Sub
Is this what you are trying?
Sub Sample()
Dim rng As Range, inp As Range
'~~> Check if what the user selected is a valid range
If TypeName(Selection) <> "Range" Then
MsgBox "Select a range first."
Exit Sub
Else
Set inp = Selection
inp.Interior.ColorIndex = 37
End If
Set rng = Application.InputBox("Copy to", Type:=8)
If Not rng Is Nothing Then
rng.Parent.Activate
rng.Select
inp.Copy
ActiveSheet.Paste Link:=True
End If
End Sub
Revised because...I didn't research. Just use this line of code after you choose the range in other sheet.
inp.Copy Destination:=ThisWorkbook.Sheets("Sheet2").Range(rng.Address)
if I
Dim rng As Range
Set rng = Range("A1")
i know rng is actually ActiveSheet.Range("A1")
then if I
Dim rngsht1 As Range
Set rngsht1 = Worksheets("Sheet1").Range("A1")
then i know rngsht1 is always on Sheet1
So now say I have a range object called "somerange", if I want to know what sheet this range is on I'll probably do this
somerange.worksheet.name
but if it gives me "Sheet1", i can't tell if it's because i have sheet1 active or because somerange is always on sheet1, without having to switch between different sheets and try again.
My question is, is there a simple way to tell whether a range object is on activesheet, or on a fixed/certain sheet? Thanks.
UPDATE: So this question is invalid. Thanks to GSerg I realized that a range object, once created, is ALWAYS on a fixed worksheet which is the worksheet the range object was created on.
Please try to use Is operator (object comparison):
If rangeObject.Worksheet Is ActiveSheet Then
' (... your code ...)
End If
Question the range's Parent
Sub MAIN()
Dim rng As Range
Set rng = Sheets(1).Range("A1")
Call IsItOnTheActiveSheet(rng)
End Sub
Sub IsItOnTheActiveSheet(r As Range)
If r.Parent.Name = ActiveSheet.Name Then
MsgBox "its on the activesheet"
Else
MsgBox "its not on the active sheet"
End If
End Sub
I have a workbook with 12 worksheets each named JANUARY through FEBRUARY.
Only the current month's sheet (e.g., NOVEMBER) will ever contain a cell containing the function =TODAY() in mm/dd/yyyy date format.
When I open the workbook, I want to automatically activate the Sheet that contains this cell (in my instance Cell N2) and Select it. I am truly a newbie learning slowly, but knowledge is minimal and can't find what I need. This what I have so far, but it doesn't work:
Sub ChooseSheet()
Dim SearchString As Variant
SearchString = "TODAY()" 'string I am searching for
Do Until SearchString = "TODAY()"
If Application.WorksheetFunction.CountIf(Sheets("Sheet1").Columns(14), SearchString) > 0 Then
Worksheets("Sheet1").Activate
End If
Exit Do
Loop
End Sub
This works for me.
Sub searchToday()
Dim sh As Worksheet
Dim found As Range
For Each sh In ActiveWorkbook.Worksheets
Set found = sh.Cells.Find(what:="=TODAY()", LookIn:=xlFormulas)
If Not found Is Nothing Then
sh.Activate
found.Select
Exit Sub
End If
Next sh
End Sub
Sub Test()
Dim ws As Worksheet
Dim f As Range
For Each ws In ActiveWorkbook.Worksheets
Set f = ws.Cells.Find(What:="=TODAY()", LookIn:=xlFormulas, LookAt:=xlWhole)
If Not f Is Nothing Then
ws.Activate
f.Select
Exit For
End If
Next ws
End Sub