VBA Excel, assign formula to row in range - vba

I am new to VBA and wanted to ask if you could help me.
I have this VB6 code:
For i = 2 To rowCount - 2
' Fill Ji with a formula(=MID(Fi,11,9)) and apply format.
Set oRng = oSheet.Range(Cells(i, 10), Cells(rowCount - 2, 10))
**oRng.formula = "=MID(Cells(i,6),11,9)"**
oRng.NumberFormat = "[$-F400]hh:mm:ss"
Next i
I want to assign a formula to the range
Tried this code but, has a problem when I assign the formula. It doesn't recognizes the Cell(i,6) as Cell, but As string "Cell(i,6)".
Can anyone help me?

You don't want the loop as you're putting the formula into all cells at once:
' Fill Ji with a formula(=MID(Fi,11,9)) and apply format.
Set oRng = oSheet.Range(oSheet.Cells(2, 10), oSheet.Cells(rowCount - 2, 10))
oRng.formulaR1C1 = "=MID(RC6,11,9)+0"
oRng.NumberFormat = "[$-F400]hh:mm:ss"
Note: I added a +0 to your formula to convert text to true time values.

Try "=MID(" & Cells(i,6).Address(False,False) &",11,9)"
Include the Address part only if you want a relative reference

Related

Replacing value in different worksheet

I have a problem and can't seem to solve it. I spend hours to try and fix it, but I can't seem to get passed the errors. Probably it is really simple for you to fix.
If you can help me, that would be amazing. I need a VBA-code to replace value X (cell found with vlookup) with a value in a different worksheet.
In the sheet: Voorraadmutatie doorvoeren I have a value in cell D4 that corresponds with a location in the sheet Voorraadbeheer stelling(en) (see images).
The value in cell D16 is the new stock so the stock in the database needs to change after activating the macro. However, to find the right cell to change I need to vlookup the right row/cell.
Sheet voorraadmutatie doorvoeren
Sheet Voorraadbeheer stelling(en)
If you could help me, that would be amazing. I have tried many things but I am not trained in using VBA. I keep getting errors and can't seem to solve it by browsing on the internet.
Thank you in advance.
I hope this example can help
Sub vLookup()
Dim SearchedValue, oldStock, newStock As Variant
Dim MyMatrix As Range
Dim No_index_col As Single
Dim ApproximateValue As Boolean
Dim n As Long
' SearchedValue = "D002"
SearchedValue = ThisWorkbook.Sheets("voorraadmutatie doorvoeren").Range("D4")
' new stock in D16
newStock = ThisWorkbook.Sheets("voorraadmutatie doorvoeren").Range("D16")
Set MyMatrix = ThisWorkbook.Sheets("voorraadbeheer stelling(en)").Range("A:C")
No_index_col = 3
ApproximateValue = False
' display the previous vlue of the stock
oldStock = Application.WorksheetFunction.vLookup(SearchedValue, MyMatrix, No_index_col, ApproximateValue)
n = 2 '2nd ligne of the matrix
Do While Not (IsEmpty(ThisWorkbook.Application.Sheets("voorraadbeheer stelling(en)").Cells(n, 1)))
If ThisWorkbook.Application.Sheets("voorraadbeheer stelling(en)").Cells(n, 1) = SearchedValue Then
ThisWorkbook.Application.Sheets("voorraadbeheer stelling(en)").Cells(n, 3) = ThisWorkbook.Sheets("voorraadmutatie doorvoeren").Range("D16").Value
End If
' next line
n = n + 1
Loop
End Sub

Finding dates and storing ranges in variables

I'm trying to find "blocks" in the worksheet that have dates in the A-column. A block is seperated by lines as you can see from the picture. The whole file is full of these blocks but I only need the blocks that have dates in the A-column. Just to be clear I don't just need the rows with the dates but the full block that contains the date.
A block in my files for example is the Range A172:G192.
Picture of the file:
[![enter image description here][1]][1]
How should I continue after selecting the first block? I probably should use the Find function starting from row 184 or the row of ResultDown variable moving down the sheet on "A" Column. However the row needs to be dynamic, so I can use it for the next block. Also I have no idea how many blocks there will be, so I would like to hear from you how to solve this aswell.
I would like to save all the blocks as different variables and then hide all the blocks in the worksheet and then just unhide the blocks that I stored in the variables.
My biggest problem is the last row.
Result2 = Range(Cells(StartcellRow, 1), Cells(1000, 1)).Find(What:="**/**/****", After:=Range(Cells(StartcellRow, 1))).Select
I keep getting an runtime error 1004
Public Sub FB_MAKRO()
Dim FBwb As Workbook
Dim FBsht As Worksheet
Dim ACol As Range
'Set variables for workbook and sheet
Set FBwb = Workbooks.Open(Filename:="C:\Users\l000xxx\Desktop\Makrot\FORCED BALANCE MAKRO\FB HARJOITUS.xls")
Set FBsht = FBwb.Sheets("Forced Balance")
Set ACol = FBsht.Range("A1:A1000")
'I want ACol variable to be the entire A-Column. Any ideas?
'For some reason the range function is not working here?
'This locates the date in A'column, so I can select the correct block
Result = Range("A3:A1000").Find(What:="**/**/****", After:=Range("A3")).Address
'This is the top left corner of the Block1 selection
ResultUp = Range(Result).End(xlUp).Offset(-1, 0).Address
Range(ResultUp).End(xlDown).Select
Range(ActiveCell, ActiveCell).End(xlDown).Select
'The ResultsDownLastRow variable is for Block2 find function
'ResultDown is the bottom right corner of the Block1
ResultsDownLastRow = Range(ActiveCell, ActiveCell).End(xlDown).Address
ResultDown = Range(ActiveCell, ActiveCell).End(xlDown).Offset(-2, 6).Address
'First Block assigned. I plan to use this in the end when I hide everything and then unhide these blocks
Block1 = Range(ResultUp, ResultDown).Select
' NEXT BLOCK STARTS HERE
'StartCellRow is the cell that the find function should start looking for Block2
'Result2 is the find function for Block2
StartcellRow = Range(ResultsDownLastRow).Row
Result2 = Range(Cells(StartcellRow, 1), Cells(1000, 1)).Find(What:="**/**/****", After:=Range(Cells(StartcellRow, 1))).Select
End Sub
'This returns value 194
StartcellRow = Range(ResultsDownLastRow).Row MsgBox StartcellRow
'This should work but doesn't. I get a syntax error
Range(Cells(StartcellRow &","& 1),Cells(1000 & "," & 1)).Find(What:="**/**/****", After:=Range(Cells(StartcellRow& ","& 1)).Select
This doesn't work either
'StarcellRow gives out value of 194
StartcellRow = Range(ResultsDownLastRow).Row
Result2 = Range("A&:StartcellRow:A648").Find(What:="**/**/****", After:=Range("A&:StartcellRow")).Select
This doesn't give me a syntax error but it's not working
I would search for all currency header and store their rownumber into an array. For each rownumber in the array i would look into the cell below (rownumber + 1). when there is a date in the cell, i would set the range in the following way:
set rangeWithDate = Range(Cells(actualRowNumberInArray - 1, 1), Cells(nextRowNumberInArray - 2, 7))
Array:
Dim array1() As long
Redim array1(5)
For i = 1 To 5
array(i) = i
Next i
Redim array1(10) ' changes the "length" of the array, but deletes old entries
For i = 1 To 10
Feld1(i) = i
Next i
Redim Preserve array1(15) ' changes the "length" of the array without deleting old entries

Multiply each value in a range by a constant, but skip blank cells

I need a simple a fast solution for multiplying all values in a range by a numeric value in VBA code. I know about this solution: Multiply Entire Range By Value?
Set rngData = ThisWorkbook.Worksheets("Sheet1").Range("A1:B10")
rngData = Evaluate(rngData.Address & "*2")
But it has a big drawback - if the original cell was blank, it results in zero. How to force it skip blank values?
I want to avoid looping through the values because it is very slow.
You can use your existing approach with Evaluate but get a little smarter with it - it can take conditions etc, so just include a test for ISBLANK. This example is tested on a combination of blank and non-blank cells in the range A1:C3 - just update for your range and give it a try:
Option Explicit
Sub Test()
Dim rng As Range
Set rng = Sheet1.Range("A1:C3")
'give the name a range so we can refer to it in evaluate
rng.Name = "foo"
'using Evaluate
rng = Evaluate("IF(ISBLANK(foo),"""",foo*2)")
'using [] notation
'preferred IMO as dont need to escape "
rng = [IF(ISBLANK(foo),"",foo*2)]
End Sub
I know you have an accepted answer, but for whatever it's worth it turns out you don't have to name the range. And in case the cells in the range contain text, then this one-line code works fine
Sub MultiplyRangeByConstant()
[A1:C3] = [IF(ISBLANK(A1:C3),"",IF(ISTEXT(A1:C3),A1:C3,2*A1:C3))]
End Sub
if there are formulas or anything else in the range:
'[a1:b3] = [{"=1","a";2,"=0/0";"",3}]
[a1:b3] = [if(a1:b3="","",if(isNumber(a1:b3),a1:b3*2,a1:b3))]
or to ignore the formulas, the good old PasteSpecial
Set temp = [c1].EntireRow.Find("") ' any blank cell that is not in the range
temp.Value = 2
temp.Copy
[a1:b3].SpecialCells(xlCellTypeConstants).PasteSpecial , Operation:=xlMultiply
temp.Value = ""

Hlookup and Match equivalent in VBA

sample.xls image
I have a code below, but it's not working properly. Something is missing in this code. Could you please help me with it?
Thanks in advance.
I added a sample.xls to show my request.
sample.xls
i dont have an error handler, my function with hlookup and match returns a value. but it returns with the same result (value) for each cell in range(N6:CQ7899). normally if i use formula in cell N6 =IFERROR(HLOOKUP(N$5,min!$C$2:$CF$7899,MATCH($E6,min!$B$2:$B$7899,0),FALSE);0) and go to last row and last col, each cell will have unique criteria with both hlookup and match. my request is how to do it by macro as follows;
do for rows in ranges N6:N7899, O6:O7899, ... and CQ6:CQ7899
N6
=IFERROR(HLOOKUP(N$5,min!$C$2:$CF$7899,MATCH($E6,min!$B$2:$B$7899,0),FALSE);0),
N7
=IFERROR(HLOOKUP(N$5,min!$C$2:$CF$7899,MATCH($E7,min!$B$2:$B$7899,0),FALSE);0)`,.,.,.,.
up to last row.
and do for columns;
O6
=IFERROR(HLOOKUP(**O$5**,min!$C$2:$CF$7899,MATCH(***$E6***,min!$B$2:$B$7899,0),FALSE);0),
O7
=IFERROR(HLOOKUP(**O$5**,min!$C$2:$CF$7899,MATCH(***$E7***,min!$B$2:$B$7899,0),FALSE);0).,.,.,.
up to last cell (CQ7899) in column CQ.
if possible, please check sample.xls image or xls file.
Function matcd()
Dim adegm As Range
Dim adizm As Range
Dim adegh As Range
Dim adizh As Range
Dim rnghFormulaCell As Range
Dim varResult1 As Variant
Set adegh = Worksheets("ara").Range("N5")
Set adizh = Worksheets("min").Range("C2:CF7899")
Set adegm = Worksheets("ara").Range("E5:E")
Set adizm = Worksheets("min").Range("B2:B7899")
Set rnghFormulaCell = Worksheets("ara").Range("N6:CQ7899") '
Worksheets("ara").Range("N6:CQ" & Rows.Count).ClearContents
varResult1 = Application.WorksheetFunction.HLookup(adegh, adizh, Application.WorksheetFunction.Match(adegm, adizm, 0), 0)
'.....
'i don't know how to Add results of varResult1 to an array in rnghFormulaCell
'.....
If Not IsError(varResult1) Then rnghFormulaCell = varResult1
End Function

Excel VBA, over flow error

I am using VBA in my excel sheet and it gives me an overlfow error. When I checked I found out that it was related to data error which shows unilmited "#" character in one cell.
All values in each cell is assigned to a string variable and when this cell comes in generates an overflow error. I tried to validate this using an if condition, but whenever we check cell.value this generates an overflow error. Is there any way to fix this?
You will not get a runtime error if you just read the cell text:
s = Range("C2").Text
Debug.Print s
' returns: "###########"
If you really want to read the cell value, and not the cell text (why you would need this, I have no idea, since you're stuffing it in a String anyway) then this is a workaround, assuming the #### are caused by dates Jan 1, 10,000 AD or later.
Const MaxDateSerial As Double = 2958466
Dim s As String
Dim dbl As Double
Dim nf As Variant
' Save original number format
nf = Range("C2").NumberFormat
' Use read-safe number format to read cell content
Range("C2").NumberFormat = "General"
dbl = Range("C2").Value
' Restore original number format
Range("C2").NumberFormat = nf
If dbl < MaxDateSerial Then
s = Range("C2").Value
Else
s = "Date overflow!"
End If
If you are doing something like
Dim s as string
Dim cl as Range
...
s = cl
' or
s = cl.value
s will be set to the value as diplayed on the sheet, which includes an error
(in the form "Error <Error Code>" if that's what the sheet displays
If the underlying cell value is valid, you should be able to access if using cl.value2
If you are doing somthing like
Dim v as Variant
Dim s as string
Dim r as Range
...
Set r = <SomeRange>
v = r
...
And one or more cells in range r are an error, then Runtime Error 6 Overflow will occur
To advise further, please post details of the code, where the error occurs, cell value and cell formatting
The ############### display for dates occurs if the date serial is before 1/1/1900 (negative) or after 1/1/9999 (> 2958101) EDIT actually 31/12/9999 = 2958465
Try using the "ISERROR()" function to filter out the invalid values.
IF(ISERROR(A1),0,A1)