Finding the cell position (row,column) by using variable - excel

I have an Excel sheet having one column as date as below :
My Job is to find to the position (cell,column) for a today's date
Script I am using :
Sub MacroExample()
Dim a As Variant
Dim column_Position As Variant
Dim row_Position As Variant
a = Format(Date - 1, "MM\/dd\/yyyy")
'MsgBox "The Value of a : " & a
Dim oRange As Range
Set oRange = Worksheets(1).Range("A1:Z10000").Find(a, lookat:=xlPart)
'MsgBox oRange.Address
MsgBox column_Position
MsgBox row_Position
End Sub
My output should be:
column_Position = 5
row_Position = 1

If I understand what you are asking, I hope this helps. This code should find the first occurrence of today's date in a specified search range.
Sub testDate()
Dim a As Variant
Dim column_Position As Variant
Dim row_Position As Variant
'get today's date, formatted m/d/yyyy
a = Format(Date, "m/d/yyyy")
Dim oRange As range
Dim myCell As range
'set a range to look through
Set oRange = Worksheets(1).range("A1:Z10000")
'check each cell value if it contains today's date. If so, capture the column and row and
'exit the loop.
For Each myCell In oRange
If InStr(1, myCell.Value, a) Then
column_Position = myCell.column
row_Position = myCell.Row
Exit For
End If
Next myCell
'display the column and row position, if wanted.
MsgBox "Column Position is " & column_Position & vbNewLine & "Row Position is " & row_Position
End Sub
Code Result
I cannot say how efficient this is, but it should work.

This will work if you look for a String within some larger string:
Sub MacroExample()
Dim a As String
a = Format(Date - 1, "MM/dd/yyyy")
MsgBox "The Value of a : " & a
Dim oRange As Range
Set oRange = Sheets(1).Range("A1:Z10000").Find(what:=a, lookat:=xlPart)
MsgBox oRange.Column
MsgBox oRange.Row
End Sub
Note:
The date includes the desired leading zeros.

Related

VBA: How to use a variable as an argument in range?

I am trying to replace the argument in a Range with a variable so I can call a sub with different variable.
Example:
sub calc(i, j As String)
.range(i:j)
end sub
sub main()
calc A1, B23
end sub
I want the final result in this case to be
.Range("A1:B23")
But I keep getting errors.
Example code which gets an error:
subscript out of range in:
If DatePart("y", Date) > DatePart("y", Sheets(s).Range(x).Value) Then
s & x are declared as Strings
Please help, thanks!
Please, test and try understanding the next approach:
Sub checDateParts()
Dim sh As Worksheet, rng As Range
Set sh = ActiveSheet
Set rng = rngCalc(sh, "A1", "B23")
MsgBox rng.Address 'returned the created range address
Set rng = rngCalc(sh, "A1")
If IsDate(rng.Value) Then 'check if the value of "A1" cell is date
MsgBox DatePart("y", Date) > DatePart("y", rng.Value)
Else
MsgBox "The value of cell """ & rng.Address & """ is not a date..."
End If
End Sub
Function rngCalc(sh As Worksheet, i As String, Optional j As String) As Range
If j <> "" Then
Set rngCalc = sh.Range(i & ":" & j)
Else
Set rngCalc = sh.Range(i)
End If
End Function
You cannot directly compare a date (today date) with a range containing more cells. You can previously extract the maximum date of the range and make the comparison with this one:
Sub checDatePartsBis()
Dim sh As Worksheet, rng As Range, maxDate As Date
Set sh = ActiveSheet
Set rng = rngCalc(sh, "A1", "B11")
MsgBox rng.Address 'returned the created range address
maxDate = DateValue(Format(WorksheetFunction.Max(rng), "dd.mm.yyyy")) ': Stop
MsgBox "Maximum date in the processed range is """ & maxDate & """ and " & vbCrLf & _
"And today is """ & Date & """."
If DatePart("y", Date) > DatePart("y", maxDate) Then
MsgBox "Yes, it is..."
Else
MsgBox "No, it is not..."
End If
End Sub
You must understand that using DatePart("y", Date) returns the day of the year. If you need/want comparing the years, you should use DatePart("yyyy", Date).
Please, test the above solution and send some feedback.

Print multiple copies of the same sheet, but replace one cell with the data from a list (range) from another sheet

I am trying to print a few months worth of time sheets. So print 20 copies of the same sheet, and change the date on one cell (cell "C1" on "Timesheets" sheet) using a list of fortnightly dates on the "Pay Periods" sheet.
Have tried multiple methods but can't get close for varying reasons...
Would be interested to learn why am getting errors or stuck on each method I have tried below.
Sub PrintAllDates()
Dim printDate As Date
Dim startDate As Date
Dim endDate As Date
startDate = Worksheets("Pay Periods").Range("A2")
endDate = Worksheets("Pay Periods").Range("A10")
For printDate = startDate To endDate
Sheets("Timesheet").Range("C1") = printDate
Sheets("Timesheet").PrintOut
Next
This works but I can't figure out how to get it to use the list.
It prints out 9 consecutive days instead, whereas my list is 9 consecutive "fortnights".
Sub PrintCopies()
Dim i As Integer
Dim VList As Variant
VList = Sheets("Pay Periods").Range("H2:H3").Value
For i = LBound(VList) To UBound(VList)
Range("C1") = VList(i)
ActiveSheet.PrintOut
Next
With the above, I get runtime error 9 "Subscript out of range" on Range("C1") = VList(i)
Sub PrintCopies()
Dim i As Date
Dim VList As Variant
VList = Array(Worksheets("Pay Periods").Range("A2:A10"))
For i = LBound(VList) To UBound(VList)
Sheets("Timesheet").Range("C1") = VList(i)
Sheets("Timesheet").PrintOut
Next
This also works, but only 1 page gets printed out.
Date also gets converted to "13 Jan 1900".
The first code does not work because it is not considering the whole range of dates; instead it takes only the value inside the first and last cell, treating them as dates. The code basically takes those dates and covers each day between them. It does not even akwnoledge the others cells between A2 and A10. This one should work:
Sub PrintAllDates()
'Declaring variables.
Dim RngDate As Range
Dim RngDates As Range
Dim RngTarget As Range
'Setting variables.
Set RngDates = Sheets("Pay Periods").Range("A2:A10")
Set RngTarget = Sheets("Timesheet").Range("C1")
'Covering each cell in RngDates.
For Each RngDate In RngDates
'Changing RngTarget.
RngTarget = RngDate.Value
'Printing RngTarget's sheet.
RngTarget.Parent.PrintOut
Next
End Sub
I've also added a feature to check if the given value is a date in this version:
Sub PrintAllDates()
'Declaring variables.
Dim RngDate As Range
Dim RngDates As Range
Dim RngTarget As Range
'Setting variables.
Set RngDates = Sheets("Pay Periods").Range("A2:A10")
Set RngTarget = Sheets("Timesheet").Range("C1")
'Covering each cell in RngDates.
For Each RngDate In RngDates
'Checking if RngDate does not contain a date value.
If Not VBA.Information.IsDate(RngDate.Value) Then
'Asking what to do in case RngDate does not contain a date value.
Select Case MsgBox("Range " & RngDate.Address(False, False) & " in sheet " & RngDate.Parent.Name & " contains the value """ & RngDate.Value & """, which is a non-date value." & vbCrLf & _
vbCrLf & _
vbCrLf & _
"Do you wish to use it and print anyway?" & vbCrLf & _
vbCrLf & _
"Press ""Yes"" to print it anyway." & vbCrLf & _
vbCrLf & _
"Press ""No"" to not print it and proceed to the next value." & vbCrLf & _
vbCrLf & _
"Press ""Cancel"" to stop the macro and print no more.", _
vbYesNoCancel, _
"Non-date value detected" _
)
'If "Cancel" is pressed, the macro is terminated.
Case Is = 2
Exit Sub
'If "Yes" is pressed, the macro goes on.
Case Is = 6
'If "No" is pressed, the macro goes to NextRngDate
Case Is = 7
GoTo NextRngDate
End Select
End If
'Changing RngTarget.
RngTarget = RngDate.Value
'Printing RngTarget's sheet.
RngTarget.Parent.PrintOut
'Checkpoint.
NextRngDate:
Next
End Sub
Your code can be something like this:
Sub PrintAllDates()
Dim listRange As Range ' Your range A2:A10 in "Pay Periods" sheet '
Dim oCurrentCell As Range ' Single cell from this range '
Dim printedSheet As Worksheet ' Target sheet - "Timesheet" '
Dim oTargetCell As Range ' C1 - target cell (to set next date from list) '
Set listRange = Worksheets("Pay Periods").Range("A2:A10")
Set printedSheet = Worksheets("Timesheet")
Set oTargetCell = printedSheet.Range("C1")
For Each oCurrentCell In listRange.Cells
oTargetCell = oCurrentCell
Rem If some cells in "Timesheet" has formulas which reffered to C1,
Rem we need recalc it before printing
printedSheet.Calculate
printedSheet.PrintOut
Next oCurrentCell
End Sub

VBA To loop each cell in the Column A in excel

In my excel in the column A, there are some date format and some text, I need to identity if each cell in column A if it is a date format or not date format:
Below is my code i try to loop each cell, but it identifies only cell A2, ANy help and ideas . Thanks
Dim strDate As String
Dim rng As Range, cell As Range
Set rng = Range("A2:A17")
With ThisWorkbook.Worksheets("Feuil1")
For Each cell In rng
MsgBox (cell.Value)
strDate = .Range("A2").Value
If IsDate(strDate) Then
MsgBox "This is a date format"
Else
MsgBox "This is not a date format"
End If
Next cell
End With
End Sub
It is because you are assigning .range("A2") to strDate; use the cell object from the for each loop:
Option Explicit
Public Sub CheckDates()
Dim strDate As String
Dim rng As Range, cell As Range
Set rng = Range("A2:A17")
With ThisWorkbook.Worksheets("Sheet1")
For Each cell In rng
MsgBox (cell.Value)
strDate = cell.Value
If IsDate(strDate) Then
MsgBox "This is a date format"
Else
MsgBox "This is not a date format"
End If
Next cell
End With
End Sub
In case you have many lines to check is better to use an array which is faster:
Sub test()
Dim i As Long
Dim arr As Variant
With ThisWorkbook.Worksheets("Feuil1")
arr = .Range("A2:A17")
For i = LBound(arr) To UBound(arr)
If IsDate(arr(i, 1)) Then
MsgBox "This is a date format"
Else
MsgBox "This is not a date format"
End If
Next i
End With
End Sub

Excel macro to reference cell text

I am putting together a basic macro to format a column to include reference letters. For example, one column has 1,2,3 and there is a cell where the user can input some letters and click a button. ABC for example. This when working shall format 1,2,3 to now be ABC1, ABC2, ABC3 etc.
I have achieved this somewhat but it only works for the letter A. See below:
Sub Macro4()
Range("A3:A60").Select
Selection.NumberFormat = Range("k11").Text & "0" & "0" & "0"
End Sub
Here's my attempt. I'm quite certain there is a better way:
Option Explicit
Sub TestMacro()
Dim MyRange As Range
Dim MyReference As Range
Dim MyArray() As Variant
Dim Counter As Long
Dim wf As WorksheetFunction
Dim Cell As Range
Dim val As Integer
Application.ScreenUpdating = False
Set wf = Application.WorksheetFunction
Set MyRange = Range("A3:A60")
For Each Cell In MyRange
val = Application.Evaluate("=MIN(SEARCH({0,1,2,3,4,5,6,7,8,9}," & Cell.Address & "&" & """0,1,2,3,4,5,6,7,8,9""" & "))")
Cell = CInt(Mid(Cell, val, Len(Cell) - val + 1))
Next Cell
Set MyReference = Range("B3")
MyArray = Application.Transpose(MyRange)
For Counter = LBound(MyArray) To UBound(MyArray)
MyArray(Counter) = MyReference & CStr(MyArray(Counter))
Next Counter
MyRange = Application.Transpose(MyArray)
Application.ScreenUpdating = True
End Sub

Excel 2010 VBA scripting

I’m a complete newbie with VBA but have managed to cobble together the following which works fine for my worksheet where I have assigned the code to a command button. My problem is that my worksheet has in excess of 3000 rows and I don’t really want to create 3000 buttons.
My current thinking would be to have a script search a range of cells for a specific condition (i.e. TRUE) then run my original code as a subscript for each cell that matches the condition. I have tried creating a loop to match the condition being searched but don't know how to set the result(s) as an active cell.
Could anyone give me some pointer on how to achieve this or propose a better solution?
Thanks.
Sub Send_FWU_to_E_Drive()
Dim aTemp As String
Dim bTemp As String
Dim cTemp As String
Dim dTemp As String
Dim eTemp As String
Dim subdir As String
aTemp = "c:\test\"
bTemp = "E:\romdata\"
cTemp = ActiveCell.Offset(, -5) & ".fwu"
dTemp = ActiveWorkbook.path
eTemp = "\Firmware files"
subdir = "\Firmware Files\" & ActiveCell.Offset(, -5) & "\" & ActiveCell.Offset(, -5) & ".fwu"
MsgBox "The path of the active workbook is " & dTemp & subdir
If Dir(dTemp & subdir) = "" Then
MsgBox "Please check the file and ensure it is suitable for firmware updating with an SD card."
Exit Sub
End If
MsgBox "The file " & cTemp & " is being copied to " & bTemp
If Dir("e:\romdata", vbDirectory) = "" Then MkDir "E:\romdata"
If Dir(bTemp & "nul") = "" Then
MsgBox "The Destination Directory is missing, please ensure your SD Card is formatted, mapped as drive E and has a romdata directory."
Exit Sub
End If
FileCopy dTemp & subdir, bTemp & cTemp
End Sub
First modify your function to accept a range argument, which we'll call cell:
Sub Send_FWU_to_E_Drive(cell as Excel.Range)
Then change all the ActiveCell references in that Sub to cell.
The sub below loops through each cell in column B of the Active sheet and, if it's TRUE, calls your routine with the cell in column A of that row. So your offsets in the code in Send_FWU_to_E_Drive are all relative to the cell in column A. This code is untested, but should be close:
Sub Test
Dim Cell as Excel.Range
Dim LastRow as Long
With ActiveSheet
LastRow = .Range("A" & .Rows.Count).End(xlup).Row
For Each Cell in .Range("B2:B" & LastRow) 'Search for TRUE in column B
If Cell.Value = TRUE Then
Send_FWU_to_E_Drive cell.Offset(0,-1) 'Column A Cell
End If
Next Cell
End With
End Sub
EDIT: Per #Siddharth's suggestion, here's a Find/FindNext version:
Sub Test()
Dim cell As Excel.Range
Dim LastRow As Long
Dim SearchRange As Excel.Range
Dim FirstFindAddress As String
With ActiveSheet
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
Set SearchRange = .Range("B2:B" & LastRow) 'Search for TRUE in column B
Set cell = SearchRange.Find(what:=True, after:=SearchRange.Cells(1))
If Not cell Is Nothing Then
FirstFindAddress = cell.Address
Send_FWU_to_E_Drive cell.Offset(0, -1)
Do
Send_FWU_to_E_Drive cell.Offset(0, -1)
Set cell = SearchRange.FindNext(after:=cell)
Loop While Not cell Is Nothing And cell.Address <> FirstFindAddress
End If
End With
End Sub

Resources