I am quite new to VBA, I have attempted to write a code below, but I'm getting a type mismatch error (Highlighted below). What I am trying to achieve is the following:
I have a list of properties on column A (all hyperlinked to their own respective sheets) on the first summary sheet called "sheet"
For each property, go to that properties sheet
Copy the value 3 cell right to the cell with the string "Total for this Property"
Switch back to "sheet" and paste the value into column D, next to the corresponding property name in column A.
I think the issue is the way I am referencing the value in the other sheet, but I can't seem to find anywhere how to reference a value that is located somewhere relative to a cell with a specific text.
Thank you in advanced!
Sub Summary()
Dim MasterBook As Workbook
Dim Sht As Worksheet
Dim Rng, Rng2 As Range
Set MasterBook = ThisWorkbook
Set Sht = MasterBook.Worksheets("Sheet")
Set Rng = Sht.Range("A6:A" & Sht.Cells(Sht.Rows.Count, "A").End(xlUp).Row)
Dim Cell As Range
For Each Cell In Rng
Cell.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
Cell.Offset(0, 3).Value = Cell.Value("Total for this Property").Offset(0, 3).Value '<---- This line is giving the error
Next Cell
End Sub
Try this
Sub Summary()
Dim MasterBook As Workbook
Dim Sht As Worksheet
Dim Rng As Range, Rng2 As Range, Rng3 As Range
Set MasterBook = ThisWorkbook
Set Sht = MasterBook.Worksheets("Sheet")
Set Rng = Sht.Range("A6:A" & Sht.Cells(Sht.Rows.Count, "A").End(xlUp).Row)
Dim Cell As Range
For Each Cell In Rng
Set Rng3 = MasterBook.Sheets(Cell.Text).Cells.Find(What:="Total for this Property", LookIn:=xlValues, LookAt:=xlWhole, _
MatchCase:=False, SearchFormat:=False)
If Not Rng3 Is Nothing Then
Cell.Offset(0, 3).Value = Rng3.Offset(, 3).Value
Else
MsgBox "not found"
End If
Next Cell
End Sub
It's no wonder that this line is giving you trouble:
Cell.Offset(0, 3).Value = Cell.Value("Total for this Property").Offset(0, 3).Value
The Value property doesn't take arguments like this! I assume you are trying the find the cell with the text Total for this Property and offset 3 from it?
In that case you should look into the Find command.
Dim myFoundCell as Range
Set myFoundCell = ActiveWorkbook.ActiveSheet.UsedRange.Find(what:="Total for this Property", lookat:=xlWhole)
If Not myFoundCell Is Nothing Then
Cell.Offset(0, 3).Value = myFoundCell.Offset(0,3).Value
End If
I think you'll also have trouble handling which workbook you're in (the ActiveWorkbook) after following a load of hyperlinks, so look into ActiveWorkbook and ThisWorkbook. What I mean is, that each range must be within a sheet on a given workbook. You're trying to copy across workbooks so will have to specify where data is going to / coming from.
Docs for Find: https://msdn.microsoft.com/en-us/library/office/ff839746.aspx
Another question when you get stuck perhaps.
I guess you're after this:
Sub Summary()
Dim Cell As Range, foundCell As Range
With ThisWorkbook.Worksheets("Sheet")
For Each Cell In .Range("A6", .Cells(.Rows.count, "A").End(xlUp))
Cell.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
Set foundCell = ActiveSheet.UsedRange.Find(what:="Total for this Property", lookat:=xlWhole, LookIn:=xlValues)
If Not foundCell Is Nothing Then Cell.Offset(0, 3).Value = foundCell.Offset(0, 3).Value '<---- This line is giving the error
Next Cell
.Activate
End With
End Sub
Since you want to "fetch" the value from a certail Worksheet (which name is placed in the cell) and not in the entire Workbook, you need to use the Find for that specific Worksheet.
The Find method syntax for that is :
Set FindRng = Worksheets(Cell.Value).Cells.Find("Total for this property")
Sub-loop Code:
Dim Cell As Range, FindRng As Range
For Each Cell In Rng
Cell.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
Set FindRng = Worksheets(Cell.Value).Cells.Find("Total for this property")
If Not FindRng Is Nothing Then ' verify that Find was successful
Cell.Offset(0, 3).Value = FindRng.Offset(0, 3).Value
End If
Next Cell
Related
I found a code but I don't why it is not working, I'm barely new to VBA. Please help me..
What I am trying to achieve is I need to Search the day today from another wb.
Here's my complete code:
Sub Sample
Sheets("Database").Select
Dim i as Workbook
Dim c as Workbook
Set i = Workbooks("Workbook1.xlsm")
Set c = Workbooks.Open(FileName:=Range("U2").Value)
'U2 contains the link or path of the file.
ThisWorkbook.Activate
Sheets("Summary").Activate
Windows("Workbook1").Activate
Sheets("Database").Select
Workbooks(2).Activate
Sheets("Summary").Select
Dim FindString As Date
Dim Rng As Range
FindString = CLng(Date)
With Sheets("Summary").Range("A:A")
Set Rng = .Find(What:=FindString, After:=.Cells(.Cells.Count), LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlbyColumns, SearchDirection;=xlNext,MatchCase;=False)
If Not Rng Is nothing then
Application.Goto Rng, True
Else
Msgbox "Nothing Then"
End if
End with
End Sub
The other workbook that was recently opened contains Summary Sheet that has Dates on Column A:A
If you're getting a syntax error - the two parameters are defined with semi-colons ";" instead of colons ":"
SearchDirection;=xlNext,MatchCase;=False
becomes
SearchDirection:=xlNext,MatchCase:=False
Fix your syntax before testing - Use Debug | Compile
Activating and Selecting is not necessary and harmful
There are also some syntax errors
You may want to re-start from the following code:
Sub Sample
Dim dbSheet as Worksheet
Dim Rng As Range
Set dbSheet = Workbooks("Workbook1.xlsm").Sheets("Database") 'set the “database” worksheet
With Workbooks.Open(FileName:=dbSheet.Range("U2").Value).Sheets("Summary") 'open the workbook whose link is in “database” sheet cell U2 and reference its “Summary” sheet
With .Range("A1", .Cells(.Rows.Count, 1).End(xlUp)) ' reference referenced sheet column A cells from row 1 down to last not empty row
Set Rng = .Find(What:=CLng(Date), After:=.Cells(.Rows.Count), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False) ' try finding current date starting from the cell at the top of referenced range
End With
End With
If Not Rng Is nothing then
Application.Goto Rng, True
Else
Msgbox "Nothing Then"
End if
End Sub
This code is untested but from the explanations in comments you can tweak it to reach the goal
Good day, I am newbie in VBA programming. need some help from experts :)
After i enter the date and click the generate button the code will find the date on the excel, but im done with this problem and here are my codes..
Dim Rng As Range
Dim FindDate As Date
FindDate = txtDate.Value
If Trim(FindDate) <> "" Then
With Sheets("Sheet2").Range("B:B")
Set Rng = .Find(What:=FindDate, After:=.Cells(.Cells.Count), LookIn:=xlValues, LookAt:=xlWhole, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True)
If Not Rng Is Nothing Then
Application.Goto Rng, True
Else
MsgBox "Nothing found"
End If
End With
End If
My next problem is, i need to select the empty cell next to the date.. Here is a screen shot
To answer your specific question, the simplest way would be:
Rng.Offset(, 1).Select
However, you ought to be aware that the Find() function when using dates can be a little unreliable. See this post for more info and links: VBA, goto cell with a certain value (type: date). Your case is particularly exposed to risk as the date is entered via a TextBox.
I have to say your code looks awfully similar to the OP's of that post. You really ought to credit code sources if you didn't write it yourself.
If I were you, I'd convert your textbox value to a Long and then search the cell values (using the .Value2 property which provides date values as Longs) for the matching Long. Code isn't much longer and could look like this:
Dim src As Range
Dim findDate As Date
Dim findVal As Long
Dim cell As Range
'Define the source data range
With Sheet2
Set src = .Range(.Cells(1, "B"), .Cells(.Rows.Count, "B").End(xlUp))
End With
'Acquire search date and convert to long
findDate = CDate(UserForm1.txtDate.Value)
findVal = CLng(findDate)
'Search for date
For Each cell In src.Cells
If cell.Value2 = findVal Then
Application.Goto cell, True
'Select the next cell to the right
cell.Offset(, 1).Select
End If
Next
you could
use a Function to try returning the wanted range
Function SetRange(FindDate As Date) As Range
If Trim(FindDate) <> "" And IsDate(FindDate) Then
With Sheets("Sheet2") '<--| reference wanted sheet
With .Range("B1", .cells(.Rows.Count, 2).End(xlUp)) '<--| reference its column "B" range from row 1 down to last not empty row
On Error Resume Next '<--| if subsequent 'Find()' avoid possible subsequent statement error to stop the Function
Set SetRange = .Find(What:=FindDate, After:=.cells(.cells.Count), LookIn:=xlValues, LookAt:=xlWhole, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True).Offset(, 1) '<--| try finding the passed 'FindDate' in referenced range and offset 1 column to the right
End With
End With
End If
End Function
and have your "Main" sub check it against Nothing before using it:
Option Explicit
Sub Main()
Dim Rng As Range
Set Rng = SetRange(txtDate.Text)
If Not Rng Is Nothing Then Rng.Select
End Sub
I am fairly new in excel VBA and would really appreciate any help on this matter.
The workbook includes data from range A5:AZ1000 (new client info is inputted in new rows, but some cells may be empty depending on the nature of the case). When a user inputs new client info (begins a new row) I would like the existing data (range A5:AZ1000) to shift down one row, and a blank row to appear in range A5:AZ:5. I would like users to be able to click a macro "New Client" for this to happen.
It should be noted that this is a shared workbook and therefore I cannot have macro that adds a new row.
Here is the code I'm working with:
Sub shiftdown()
' shiftdown Macro
Dim lastRow As Long
Dim lastColumn As Long
Dim rngToCopy As Range
Dim rng As Range
Set rng = ActiveSheet.Range("A1").Value
lastColumn = ActiveSheet.Cells(4, Columns.Count).End(xlToLeft).Column
lastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
If rng > 0 Then
ActiveSheet.Range("A5" & lastRow).Select
Selection.Copy
PasteSelection.Offset(1, 0).PasteSpecial xlPasteValues
'Error Object Required
End If
End Sub
Normally I wouldn't answer if the question doesn't include any code to show effort, but I started writing the below while the question actually did show code so I may as well provide it. It may achieve what you are after.
Sub shiftdown()
' shiftdown Macro
Dim rng As Range
With ActiveSheet
If .Range("A1").Value > 0 Then
Set rng = .Range(.Cells(5, 1), _
.Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, _
.Cells(4, .Columns.Count).End(xlToLeft).Column))
rng.Offset(1, 0).Value = rng.Value
.Rows(5).EntireRow.ClearContents
End If
End With
End Sub
Set rng = ActiveSheet.Range("A1").Value ???
if rng is a range, then replace it by :
Set rng = ActiveSheet.Range("A1")
or if rng is a variable, replace
Dim rng As Range
by
Dim rng As variant
rng = ActiveSheet.Range("A1").Value
another error :
you declared rng as range and then you test if it is > 0
If rng > 0 Then ...
it is not possible
I hope you can help. I have a some code below which works fine. What it does is opens up a dialog box allows a user to select an excel file, once this file is selected.
The code looks through the column headings find the Text "CountryCode" then cuts this column puts it into Column F then separates column F into new worksheets based on the country.
This issue I am facing is that sometimes the the column I want to cut contains the text "ClientField10" or "ClientField1"
So what I would like the macro to do is search the column headings for "CountryCode" if this is found fine execute the rest of the code.
If it is NOT found search for "CleintField10" then if found execute and if neither "CountyCode" or "CleintField10" is found search for "CleintField1" then execute the rest of the code
My code is below as always any help is greatly appreciated.
Sub Open_Workbook_Dialog()
Dim my_FileName As Variant
Dim my_Workbook As Workbook
MsgBox "Pick your TOV file" '<--| txt box for prompt to pick a file
my_FileName = Application.GetOpenFilename(FileFilter:="Excel Files,*.xl*;*.xm*") '<--| Opens the file window to allow selection
If my_FileName <> False Then
Set my_Workbook = Workbooks.Open(Filename:=my_FileName)
Call Sample(my_Workbook) '<--|Calls the Filter Code and executes
Call Filter(my_Workbook) '<--|Calls the Filter Code and executes
End If
End Sub
Public Sub Sample(my_Workbook As Workbook)
Dim ws As Worksheet
Dim aCell As Range, Rng As Range
Dim col As Long, lRow As Long
Dim colName As String
'~~> Change this to the relevant sheet
Set ws = my_Workbook.Sheets(1)
With ws
Set aCell = .Range("A1:BB50").Find(What:="CountryCode", LookIn:=xlValues, LookAt:=xlWhole, _
MatchCase:=False, SearchFormat:=False)
'~~> If Found
If Not aCell Is Nothing Then
'~~> Cut the entire column
aCell.EntireColumn.Cut
'~~> Insert the column here
Columns("F:F").Insert Shift:=xlToRight
Else
MsgBox "Country Not Found"
End If
End With
End Sub
Public Sub Filter(my_Workbook As Workbook)
Dim rCountry As Range, helpCol As Range
With my_Workbook.Sheets(1) '<--| refer to data worksheet
With .UsedRange
Set helpCol = .Resize(1, 1).Offset(, .Columns.Count) '<--| get a "helper" column just at the right of used range, it'll be used to store unique country names in
End With
With .Range("A1:Q" & .Cells(.Rows.Count, 1).End(xlUp).Row) '<--| refer to its columns "A:Q" from row 1 to last non empty row of column "A"
.Columns(6).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=helpCol, Unique:=True '<-- call AdvancedFilter on 6th column of the referenced range and store its unique values in "helper" column
Set helpCol = Range(helpCol.Offset(1), helpCol.End(xlDown)) '<--| set range with unique names in (skip header row)
For Each rCountry In helpCol '<--| iterate over unique country names range (skip header row)
.AutoFilter 6, rCountry.Value2 '<--| filter data on country field (6th column) with current unique country name
If Application.WorksheetFunction.Subtotal(103, .Cells.Resize(, 1)) > 1 Then '<--| if any cell other than header ones has been filtered...
Worksheets.Add Worksheets(Worksheets.Count) '<--... add new sheet
ActiveSheet.Name = rCountry.Value2 '<--... rename it
.SpecialCells(xlCellTypeVisible).Copy ActiveSheet.Range("A1") 'copy data for country under header
End If
Next
End With
.AutoFilterMode = False '<--| remove autofilter and show all rows back
End With
helpCol.Offset(-1).End(xlDown).Clear '<--| clear helper column (header included)
End Sub
Because I didn't get to test my code before, I made the silly mistake of using "If" instead of an "ElseIf" statements. I tested the below code and now it works.
Sub test()
Dim acell As Range
Dim ws As Worksheet
Set ws = ActiveWorkbook.Sheets(1) 'define ws
Set acell = ws.Range("A1:BB50").Find(What:="CountryCode", LookIn:=xlValues, LookAt:=xlWhole, _
MatchCase:=False, SearchFormat:=False) 'define acell as location of "countrycode"
If Not acell Is Nothing Then 'if address is found do the cut & insert of that column
acell.EntireColumn.Cut
Columns("F:F").Insert Shift:=xlToRight
ElseIf acell Is Nothing Then 'if address is not found redefine acell to look for "clientfield10"
Set acell = ws.Range("A1:BB50").Find(What:="ClientField10", LookIn:=xlValues, LookAt:=xlWhole, _
MatchCase:=False, SearchFormat:=False)
If Not acell Is Nothing Then 'if address is found do the cut & insert
acell.EntireColumn.Cut
Columns("F:F").Insert Shift:=xlToRight
ElseIf acell Is Nothing Then 'If not found redefine acell again to look for "ClientField1"
Set acell = ws.Range("A1:BB50").Find(What:="ClientField1", LookIn:=xlValues, LookAt:=xlWhole, _
MatchCase:=False, SearchFormat:=False)
If Not acell Is Nothing Then 'If found do cut and insert
acell.EntireColumn.Cut
Columns("F:F").Insert Shift:=xlToRight
Else: MsgBox "Country Not Found" 'If none can be found display msgbox
End If
End If
End If 'close all the If loops
End Sub
I will delete my old answer to make this thread easier to understand
I have a wordbook with multiple sheets. I have a sheet called “Info” that contains hundreds of rows of employees. Each employee is assigned an employee number in column B; the remainder of the row (24 columns) contains the rest of the employee’s personal information).
I have another sheet called “data” that only requires a group of 20 to 40 people that can vary from day to day
I want to be able to enter an employee number (ex: SN124523) into an empty cell in column B on Sheet called “Data”. I would then like the remainder of the row to self-populate with the employee information from the “Info” sheet.
I need to do this with up to 40 employees, so regardless of which cell I select in column B on the “Data” sheet I would like it to search the “info “sheet on import the information.
I have made this work with a VLOOKUP formula, but because multiple people sometimes use this book and I sometime have to delete and replace the "info" Sheet That I always end up with a #REF error in the formulas.
I tried something like this for just a few lines of data as a trial but I can’t get anything to work.
Sub Add_member()
Dim ws As Worksheet
Dim ws1 As Worksheet
Dim iRow, row_count As Long
Set ws = Worksheets("Info")
Set ws1 = Worksheets("Data")
row_count = ws.Range("B" & Rows.Count).End(xlUp).Row
For iRow = 2 To row_count
If ws1.Cells(iRow, 2) = ws.Cells(iRow, 2) Then
ws1.Cells(iRow, 4).Value = ws.Cells(iRow, 4).Value
ws1.Cells(iRow, 5).Value = ws.Cells(iRow, 5).Value
‘ I would need this to fill 24 columns in total.
End If
Next
End Sub
Any help Much Appreciated.
I would use an Event_Handler in this situation. Therefore when you enter the number the data is automatically updated for you.
Assuming B1 is the cell you will be entering the number to be looked up.
Post the below code into the WorkSheet module, enter a number and the data should appear for that number in row 1
Private Sub Worksheet_Change(ByVal Target As Range)
Dim fCell As Range
Dim rng As Range
Application.EnableEvents = 0
Set ws = Worksheets("Info")
If Not Intersect(Target, Range("B1")) Is Nothing Then
Set fCell = ws.Range("B2:B1000").Find(What:=Target, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not fCell Is Nothing Then
Target.Resize(, 24).Value = fCell.Resize(, 24).Value
Else
MsgBox "No number exists."
Range("B1:Y1").ClearContents
End If
End If
Application.EnableEvents = 1
End Sub
assuming
employee number is a string (like "SN124523")
there's always one employee number at least
employee numbers are input in a contiguous range in sheet "data" column B (i.e. n blanks between them)
then you could use
Sub Add_member()
Worksheets("Data").Columns(2).SpecialCells(xlCellTypeConstants, xlTextValues).offset(, 2).Resize(, 24).FormulaR1C1 = "=Vlookup(RC2,Info!C2:C27,column()-1)"
End Sub
or, should you want to get rid of formulas:
Sub Add_member()
With Worksheets("Data").Columns(2).SpecialCells(xlCellTypeConstants, xlTextValues).offset(, 2).Resize(, 24)
.FormulaR1C1 = "=Vlookup(RC2,Info!C2:C27,column()-1)"
.value = .value
End With
End Sub
of course all the above assumptions can be removed and the code changed accordingly.
but the one above just to show the shortest possible
Untested:
Sub Add_member()
Dim ws As Worksheet
Dim ws1 As Worksheet
Dim f As Range, c As Range, rng As Range
Set ws = Worksheets("Info")
Set ws1 = Worksheets("Data")
Set rng = ws1.Range("B2", ws1.Cells(Rows.Count, 2).End(xlUp))
For Each c In rng.Cells
If Len(c.Value) > 0 Then
Set f = ws.Columns(2).Find(what:=c.Value, LookIn:=xlValues, _
lookat:=xlWhole)
If Not f Is Nothing Then
c.Offset(0, 2).Resize(1, 24).Value = _
f.Offset(0, 2).Resize(1, 24).Value
End If
End If
Next
End Sub