Dim worksheet1 As Worksheet
Set worksheet1 = ActiveSheet
Dim workbook2 As Workbook
Set workbook2 = Workbooks.Open(("F:\Project Sweep\Kim Checklist\" & worksheet1.Cells(19, 12) & "\Consumers.xlsx"))
Dim targetString As String
targetString = "index('" & workbook2.Path & "\[" & workbook2.Name & "]Time'!$A$1:$E$366, 1, 1)"
Dim i As Long
For i = 0 To 4
worksheet1.Cells(7 + (i * 2), 7) = Application.Calculate(targetString)
Next i
The code is attempting to do the following:
From worksheet 1, where the function is supposed to be called, it is supposed to pull from the worksheet Time in workbook 2, the value located at cell A1 (to be updated later to be iterative when the code is working), and place it in cell(7,7), cell(9, 7), cell(11, 7) and so on.
The above code is giving the error "Compile Error: wrong number of arguments or invalid property assignment"
The other option I was using was
worksheet1.Range(Cells(7 + (i * 2), 7)).Formula = "=" & targetString
literally just placing the formula in the cell. But that gives the error "Run time error 1004: method range of object failed"
Any help would be appreciated thank you in advance for your time.
You're looking for Application.Evaluate, not Application.Calculate.
For i = 0 To 4
worksheet1.Cells(7 + (i * 2), 7) = Application.Evaluate(targetString)
Next i
I'm a little unclear on what is going to change during that loop since the string that looks like a formula is static throughout.
Use .Address with External:=True to resolve a complete external path, workbook, worksheet and range.
with workbook2.worksheets("Time").range("A1:E366")
targetString = "index(" & .address(external:=true) & ", 1, 1)"
debug.print targetString
end with
Related
This question already exists:
VBA delete entire row with number (variable of For loop)
Closed 2 years ago.
thank you all in advance for your help. I'm not an advanced coder at all but in some way managed to make to following code work, except one really basic thing.I'm struggling with a very basic issue namely the actual deleting of 1 row every time the condition is not getting fulfilled. And the number of the row should be taken from a FOR loop. The coordinate in which the FOR loop is currently positioned should be reflected by S.Row but as I showed below, I've been trying multiple ways of deleting it and I get always an error with "Run-time error '1004': Application-defined or object-defined error" It's driving me crazy, please help. ONE MORE TIME THANK YOU ALL:
Public Sub Optionfilter()
Dim StrikeD As Date
Dim RefD As Date
Dim StrikeP As Integer
Dim S As Range
Dim R As Range
Dim XVAR As Integer
Dim Intervall As String
Dim Number As Integer
Dim TotalRow As Integer
Dim L As Integer
XVAR = 5
Intervall = ThisWorkbook.Worksheets("Data").Range("I2").Value
Debug.Print Intervall
Number = ThisWorkbook.Worksheets("Data").Range("G2").Value
Debug.Print Number
Debug.Print ThisWorkbook.Worksheets("Data").Range("G2").Address
Debug.Print "-----------------------------------------"
XP:
For Each S In ThisWorkbook.Worksheets("Data").Range("J6:J" & ThisWorkbook.Worksheets("Data").UsedRange.SpecialCells(xlCellTypeLastCell).Row)
Debug.Print S.Address & " in the Calc Loop"
Debug.Print ThisWorkbook.Worksheets("Data").UsedRange.Cells(S.Row, S.Column - 1).Value
Debug.Print ThisWorkbook.Worksheets("Data").UsedRange.Cells(S.Row, S.Column - 1).Address
StrikeD = ThisWorkbook.Worksheets("Data").UsedRange.Cells(S.Row, S.Column - 1).Value
Debug.Print StrikeD
Debug.Print "-----------------------------------------"
RefD = ThisWorkbook.Worksheets("Data").Range("E2").Value
Debug.Print RefD
RefD = DateAdd(Intervall, Number, RefD)
Debug.Print RefD
DIFFRAW = Abs(StrikeD - RefD)
Debug.Print DIFFRAW
ThisWorkbook.Worksheets("Data").UsedRange.Cells(S.Row, S.Column + 1).Value = DIFFRAW
If ThisWorkbook.Worksheets("Data").UsedRange.Cells(S.Row, S.Column + 1).Value > XVAR Then
Debug.Print S.Row
L = S.Row
'This code below is not deleting anything for some reason it's just getting executed but no row disappear/delete
Rows(S.Row).EntireRow.Delete
'This code below is also not deleting anything for some reason it's just getting executed but no row disappear/delete
Range("J" & S.Row).EntireRow.Delete
'This code below is giving me the mentioned ERROR
'ThisWorkbook.Worksheets("Data").Rows(L).Delete
'OR Run-time error 438
ThisWorkbook.Worksheets("Data").S.EntireRow.Delete
'OR
Range("A" & S.Row).EntireRow.Delete
'OR
ThisWorkbook.Worksheets("Data").Rows("S.Row").Delete
'OR
ThisWorkbook.Worksheets("Data").Range(S, 1).EntireRow.Delete
Else
End If
Next S
TotalRow = ActiveSheet.UsedRange.Rows.Count
Debug.Print TotalRow
Debug.Print ThisWorkbook.Worksheets("Data").UsedRange.Cells(S.Row, S.Column).Address
Debug.Print ThisWorkbook.Worksheets("Data").UsedRange.Cells(S.Row, S.Column).Value
Sheets.Add After:=Worksheets("Data") 'After we deleted the old datasheet, we now insert a new (empty) one
Sheets(3).Name = "TEMP" 'and rename it instead of the defaultname to
If TotalRow <= 10 Then ' And ThisWorkbook.Worksheets("Data").UsedRange.Cells(S.Row, S.Column).Value > 0 Then
For Each R In ThisWorkbook.Worksheets("Data").Range("J6:J" & ThisWorkbook.Worksheets("Data").UsedRange.SpecialCells(xlCellTypeLastCell).Row)
ThisWorkbook.Worksheets("Data").UsedRange.Cells(S.Row).Copy
ThisWorkbook.Worksheets("Temp").Cells(j, 2).PasteSpecial xlPasteValues
j = j + 1 'This is a controlvariabel to write the copied cell everytime in a new row
Next R
Else
XVAR = XVAR - 1
GoTo XP
End If
End Sub
'S eine erste Position zu ordnen
'zusätzlichen Goto einfpügen falls 0 resultate sind und schleife mit Prioritisierung der ergebnisse -->besser davor als danahc usw.
' Debug.Print ActiveSheet.Cells(S.Row, S.Column + 7).Value
's.Value = Replace(s.Value, ",", "") 'delete the ","
' If InStr(1, S, "S") > 0 Then 'The command InStr(1, s, "S") respond the place (position) where it found "S" in the cellstring
' '(s), for example: 1/5/3... basically it looks if in this cell the letter appears
' S.Value = Replace(S.Value, " ", "") 'If it has found an "S" in the cell value (for example in the portgolionumber
' '011 1044 S02) then it replaces all " " by "" and write the new value (0111044S02) in the cell
' End If 'Ends the if condition
I can't follow what you posted here but this addresses the core of your original question:
Dim i As Long, ws As Worksheet, XVAR As Long
Set ws = ThisWorkbook.Worksheets("Data")
'XVAR = '...something
For i = ws.Cells(Rows.Count, 10).End(xlUp).Row To 6 Step -1
If ws.Cells(i, 11).Value > XVAR Then
ws.Rows(i).Delete
End If
Next i
This may or may not be related to the issue you are having, but I'm writing as an answer to help with misunderstandings it looks like you are having.
Your variable S is a range. As such excel knows everything about that range when you set it. It knows it's value, it's row and column, the sheet in which it's contained, and the workbook in which that sheet is contained. All of your code where you qualify your S variable or pulling the row only to use it's Long value to refer to the same row... is superfluous at best and causing errors at worse.
For instance:
Rows(S.Row).EntireRow.Delete
You are literally saying "Grab the number representing the row in which this cell resides and in whatever worksheet is currently active (who knows what that is...?), delete the entire row that corrsponds to that number".
Instead:
S.EntireRow.Delete
Now it says "Delete the entire row in which the cell held in variable S resides".
As for your error:
ThisWorkbook.Worksheets("Data").S.EntireRow.Delete
This says "The cell in variable S, for which we already know which sheet and workbook it resides by the nature of the range object being held in this variable, (let me tell you regardless though) that's specifically in ThisWorkbook and the Worksheet called Data delete it's entire row."
Excel isn't down with this because you can't qualify a range object like this with a worksheet and workbook. It's already set and unchangeable. Range S is already 100% unchange-ably in Sheet "Data" and ThisWorkbook. Your attempt to tell excel this information again is just making excel angry.
Instead:
S.EntireRow.Delete
Which looks familiar.
thank you very much for the elaboration and the time you took for it. I really appreciate it, thank you. It makes all sense, but after copying your code ( S.EntireRow.Delete) into my syntax I receive always the same error stated here: https://qph.fs.quoracdn.net/main-qimg-0ea61a60a22c8fbbbf3e95c1b463b242
I've just created a brand new macro. Took function down below from internet (all credits goes to trumpexcel.com), code down below
Function CONCATENATEMULTIPLE(Ref As Range, Separator As String) As String
Dim Cell As Range
Dim Result As String
For Each Cell In Ref
Result = Result & Cell.Value & Separator
Next Cell
CONCATENATEMULTIPLE = Left(Result, Len(Result) - 1)
End Function
Then I proceed to extract data from various columns and into the one (my table is 20 rows x 10 columns)
Sub conact_data()
Dim i As Integer
For i = 2 To Cells(Rows.Count, "A").End(xlUp).Row
Cells(i, "M").Value = Cells(i, "A").Value & " " & _
Cells(i, "B").Value & " / " & Cells(i, "D").Value & "; "
Next i
End Sub
Thanks to that I've got combined data from column A, B and D, so its 20 rows. All I want to do now is to concatenate data from M2:M21 using CONCATENATEMULTIPLE function therefore I try various approach (I want this huge line in P2 cell) like :
Cells(2, 16).Value = CONCATENATEMULTIPLE (M2:M21, " ")
or
Range("P2") = "CONCATENATEMULTIPLE (M2:M21, " ")"
I don't really know how to apply that
Secondly, I'd like withdraw the Cells(i, "B").Value as percentage. Can I do that in one line like Cells(i, "B").NumberFormat="0.00%".Value (which is not working for me obviously) else I need to copy column B into another column with number format and then combine the new column, properly formatted instead of column B?
Thanks in advance
Percent format: Range("B" & i).NumberFormat = "0.00%"
CONCATENATEMULTIPLE
In VBA, CHR(32) = " "
In Excel, CHAR(32) = " "
With that being said...
'Value
Range("P2").Value = CONCATENATEMULTIPLE(Range("M2:M21"), CHR(32))
'Formula
Range("P2").Formula = "=CONCATENATEMULTIPLE(M2:M21, CHAR(32))"
You should really qualify all of your ranges with a worksheet
Say your workbook has 10 sheets. When you say Range("P2"), how do we (VBE) know what sheet you mean? Objects need to be properly qualified. Sometimes this is not a huge issue, but when you are working across multiple sheets, not qualifying ranges can lead to some unexpected results.
You can qualify with a worksheet a few ways.
Directly: ThisWorkbook.Sheets("Sheet1").Range("P2").Copy
Or use a variable like so
Dim ws as Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
ws.Range("P2").Copy
Now there is no room for ambiguity (potential errors) as to the exact location of Range("P2")
First of all, remove your ConcatenateMultiple() code, and instead use Excel worksheet function CONCAT(), which takes a range and a delimiter as parameters.
Here is how you can handle the percentage issue and supply a default for non-numeric items. I've also cleaned up the way you reference your data range.
Sub concat_data()
Dim rngRow As Range, vResult As Variant
Const DEFAULT = 0 'Can also be set to a text value, eg. "Missing"
For Each rngRow In [A2].CurrentRegion.Rows
If IsNumeric(rngRow.Cells(, 4)) Then vResult = rngRow.Cells(, 4) * 100 & "%" Else vResult = DEFAULT
Range("M" & rngRow.Row) = rngRow.Cells(, 1) & rngRow.Cells(, 2) & "/" & vResult & ";"
Next
[M2].End(xlDown).Offset(1).Formula = "=CONCAT(M2:M" & [M2].End(xlDown).Row & ",TRUE,"" "")"
End Sub
I'm not a fan of hard-coding range references, like the [A2] or Range("M"), but will leave that for another time.
Here is some of my code:
Dim wbX As Workbook
Dim wbY As Workbook
Set wbX = Application.Workbooks.Open("C:\Converter\aaa.xls")
Set wbY = Application.Workbooks.Open("C:\Converter\bbb.xlsx")
For i = 1 To wbX.Sheets.Count
wbY.Sheets(1).Activate
Range("Y" & i + 2).Select
ActiveSheet.Range("Y" & i + 2).Formula = "=RIGHT(("S" & i + 2); 4)"
The problem is that ("S" & i + 2) is not recognized as a cell - VBA spits out syntax errors.
Your expression "Y" & i + 2 does not yield a valid cell reference because you concatenate a number to a string. You must convert the numeric expression to a string:
"Y" & Str(i + 2)
What I understand from your comment, the assignment should be written as:
"=LEFT(S" & Trim(Str(i + 2)) & "; 4)" ' yields e.g.: =LEFT(S3; 4)
(The LEFT function gets the first characters from a string. This assumes the cells you reference contains strings, or that VB converts the value to a string first. And here you must use Trim(Str(i + 2)) because you are constructing a string to place as a formula in the cell.)
Maybe this example helps you:
Option Explicit
Sub test()
Dim rngC As Range
For Each rngC In Range("C2:C100")
rngC.Offset(0, 4) = Right(rngC, 4)
Next
End Sub
I'm trying to get this segment of code to execute. This is a simplified version of the code. I've included the relevant code. I'm trying to concatenate strings and named ranges into a SumIfs formula, but I get error 1004 "Application-defined or Object-defined error." I have a working line of code above this problem section that is similar with the exception of doing a sum function, instead of sumif. Any idea how to get this code to execute? Thank you.
Dim wb As Workbook
Dim ara As Worksheet
Dim inv As Worksheet
Dim ARBlock As Range
Dim Invoices As Range
Dim AgedDays As Range
Set wb = ThisWorkbook
Set ara = wb.Sheets("AR Aging")
Set inv = wb.Sheets("Invoices")
Set ARBlock = ara.Range("a6")
Set Invoices = inv.Range("a6", inv.Range("a6").End(xlDown))
Set AgedDays = Invoices.Offset(0, 6)
'Populate A/R age buckets
For i = 6 To ARBlock.Rows.Count + 6
With ARBlock(i - 5, 1).Offset(0, 3)
.Value = "=SumIfs(" & Invoices.Offset(0, 4).Address & "," & _
Invoices.Address & "," & ARBlock(i - 5, 1).Value & "," & _
Invoices.Offset(0, 6).Address & ","" <= "" & &O30)"
End With
Next i
End Sub
The line beginning with ".value" is where I'm getting the error message. P.S.: I need the cell to contain the concatenated formula, as opposed to the output value.
UPDATE 1:
As some suggested I updated the .value line to:
.Offset(0, 3).Formula = "=SumIfs(Invoices.Offset(0, 4).Address,Invoices.Address,ARBlock.cells(i - 5, 1).Value)"
I'm still getting the same error. Some auditing I've done:
Removing the "=" before "Sumifs" allows the code to run fine; pasting in the formula into the target cell as text. In this form, my output for i=1 goes to ARBlock.cells(1,1), as it should.
I also used Debug.Print to view all of the components of the formula:
Debug.Print ARBlock.Cells(i - 5, 1).Address
'output $A$6
Debug.Print ARBlock.Cells(i - 5, 1).Value
' output International Business Machines
Debug.Print Invoices.Offset(0, 4).Address
'output $E$6:$E$255
Debug.Print Invoices.Address
'output $A$6:$A$255
I suspected the issue might be that the range dimensions might have been off, but this is not the case. My next suspicion is that the output International Business Machines needs to be in " " for the formula to read it correctly. I hardcoded in
""International Business Machines""
to see if this would fix the formula, but I keep getting the same error once I add the "=" back in. The formula syntax is correct, the dimensions are the same between the sum range and criteria range. Anyone else have any ideas?
.Offset(0, 3).Formula = "=SumIfs(Invoices.Offset(0, 4).Address,Invoices.Address,ARBlock.cells(i - 5, 1).Value)"
Change to:
.Offset(0, 3).Formula = "=SumIfs(" & Invoices.Offset(0, 4).Address & ", " & Invoices.Address & ", " & chr(34) & ARBlock.Cells(i - 5, 1).Value & chr(34) & ")"
EDIT: Added quotes chr(34) around your string!
Your ARBlock(i - 5, 1).Value most likely is an empty cell, which messes the SUMIFS formula as it builds it with to consecutive commas
I have a problem with my hyperlink in excel. Im trying to set a hyperlink from one sheet to another but the source and target cell needs to change every time in the loop. Basically i want to move data from one cell in GROUP 1 to another cell in GROUP 2 then set a hyperlink from GROUP 2 back to the same cell in GROUP 1. I have like 200 values so i want to do this in a loop. I just can´t figure out whats wrong whit my SubAddress!!
This is my code below.....
Thank you for any help.
Sub Transfer_and link()
Dim i As Integer
Dim LastRow1, As Long
LastRow1 = Sheets("GROUP 1").Cells(Rows.Count, "A").End(xlUp).Row
a = 14
For i = 5 To LastRow1 Step 2
Sheets("GROUP 2").Cells(a, 2) = Sheets("GROUP 1").Cells(i, 1)
Sheets("GROUP 2").Cells(a, 3) = Sheets("GROUP 1").Cells(i, 9)
Sheets("GROUP 2").Cells(a, 4) = Sheets("GROUP 1").Cells(i, 10)
Sheets("GROUP 1").Activate
Cells(i, 1).Select
Worksheets(2).Hyperlinks.Add Anchor:=Worksheets(2).Cells(a, 2), Address:="", _
SubAddress:=ActiveCell.Address
a = a + 1
Next i
ActiveCell.Address only returns the cell reference. You need to add the sheet reference too.
It'd be something like:
SubAddress:=ActiveCell.Worksheet.Name & "!" & ActiveCell.Address
If your sheet name may have a space like yours, it'd actually have to be this:
SubAddress:="'" & ActiveCell.Worksheet.Name & "'!" & ActiveCell.Address