I am trying to make a sum formula on a dynamic range. Much like in a pivot table.
Taking a look on the picture I want L15 to be the sum of the range from L16 to the blank row. As the range is dynamic I am not sure how to write it on my code. So far what I have is this:
If out.Range("A15").Cells(i, 1) = "Aktier" Then
out.Range("L15").Cells(i, 1) = Application.WorksheetFunction.Sum(Range("L15").Cells(i + 1, 1), Range("L15").Cells(i + 1, 1).End(xlDown))
End If
So my question is basically how do I write something like Sum(A1:End(xlDown))? :)
Hope you can help me out guys! :D
Thanks in advance!
First I would recommend that every time that's possible, you get a structure more Data Base-like, so I would have a column repeating the concept and then you could use the Excel SUMIF function easily.
Probably that's not your case (that seems the output of an accounting program). Taking advantage of using VBA macros, you can use a loop to generate the column I mentioned before (you could do the sum as well using the concept, but I believe is cleaner generating a better data format). Please see the image below:
Sub Add_Concepts()
i = 1
Concept = Cells(i, 2)
i = 2
Do While (Cells(i, 2) <> "")
Cells(i, 1) = Concept
If Cells(i + 1, 2) = "" Then 'Change in concept
Concept = Cells(i + 2, 2) 'New concept
i = i + 2 'add 2 to skip the New concept line and the white space
End If
i = i + 1
Loop
End Sub
Now you can use the regular Excel functions.
Hope this helps!
Skipping Steps
Snippet:
If out.Range("A15").Cells(i, 1) = "Aktier" Then
With out.Range("L15")
.Cells(i, 1) = Application.WorksheetFunction _
.Sum(.Parent.Range(.Offset(1), .Offset(1).End(xlDown)))
End With
End If
Working example:
Option Explicit
Sub SumToBlank()
Dim out As Worksheet: Set out = ThisWorkbook.Worksheets("Sheet1")
Dim i As Long: i = 1
If out.Range("A15").Cells(i, 1) = "Aktier" Then
With out.Range("L15")
.Cells(i, 1) = Application.WorksheetFunction _
.Sum(.Parent.Range(.Offset(1), .Offset.End(xlDown)))
End With
End If
End Sub
Related
I am writing a VBA script to check all measuring point, who are part of the selection have inspection orders. For this I need to extract a large amount of measering point (ca. 2721) and use them as an input in another transaction.
The problem I have is: What is the most efficient way to extract / export a large amount of data from SAP in a way that I can paste them as an input in SAP?
I can make an export, but I cannot access the exported Excel-file through VBA. I can loop through the datarows and copy every single cell, but this is very slow, as shown below.
row = 1
For i = 1 To session.FindById("wnd[0]/usr/cntlGRID1/shellcont/shell").RowCount - 2
session.FindById("wnd[0]/usr/cntlGRID1/shellcont/shell").CurrentCellRow = i
ThisWorkbook.Sheets("Output2").Cells(row, 1) = session.FindById("wnd[0]/usr/cntlGRID1/shellcont/shell").GetCellValue(i - 1, "TPLNR")
ThisWorkbook.Sheets("Output2").Cells(row, 2) = session.FindById("wnd[0]/usr/cntlGRID1/shellcont/shell").GetCellValue(i - 1, "POINT")
row = row + 1
Next
You should
use an array - instead of writing directly to the sheet
use with to not call session.FindByID... multiple times
Dim arrData As Variant, i As Long
With session.FindById("wnd[0]/usr/cntlGRID1/shellcont/shell")
ReDim arrData(1 To .RowCount - 2, 1 To 2)
For i = 1 To .RowCount - 2
.CurrentCellRow = i
arrData(i, 1) = .GetCellValue(i - 1, "TPLNR")
arrData(i, 2) = .GetCellValue(i - 1, "POINT")
Next
End With
With ThisWorkbook.Sheets("Output2")
.Resize(UBound(arrData, 1), 2).Value = arrData
End With
But maybe it's worth to look into Powerquery to achieve what you want.
For i = i To nr_commercial
Cells(i, 1) = commercial & RandBetween(1, 6)
Next i
Hi All - I have the above but I am not able to solve it. It returns a compiler error every time. I'm having issues putting a string plus a formula together.
commercial is defined as a string
I have even tried
Cells(i, 1) = commercial & = Randbetween(1,6)
and it returns error saying expecting expression. Is there something not right with the randbetween functionality?
I need to have output in cells such like:
commercial-1
commercial-5
commercial-3
Try:
Application.WorksheetFunction.RANDBETWEEN(1,6)
For example:
Sub qwerty()
Dim nr_commercial As Long, commercial As String
nr_commercial = 10
commercial = "whatever"
For i = 1 To nr_commercial
Cells(i, 1) = commercial & Application.WorksheetFunction.RandBetween(1, 6)
Next i
End Sub
(also fixed the loop index)
Try this
For i = i To nr_commercial
Cells(i, 1) = "commercial-" & Application.WorksheetFunction.RANDBETWEEN(1,6)
Next i
Edited : Application.WorksheetFunction.RANDBETWEEN(1,6) is the correct formula to be used
Also it is not advisable to use Cells try to use Sheet or Worksheet in your code.
I think your issue is that you are using For i = i To nr_commercial which means every iteration it is changing "For 1 = 1 to nr_commercial" and then "2 = 2 to nr_commercial" which doesn't make sense. It should be For i = 1 to nr_commercial or whatever cell you want to start at, probably not in the first cell, as you are likely to have headers.
Please be aware that I am working with a series of ~1000 line medical information databases. Due to the size of the databases, manual manipulation of the data is too time consuming. As such, I have attempted to learn VBA and code an Excel 2010 macro using VBA to help me accomplish parsing certain data. The desired output is to split certain characters from a provided string on each line of the database as follows:
99204 - OFFICE/OUTPATIENT VISIT, NEW
will need to be split into
Active Row Active Column = 99204 ActiveRow Active Column+3 = OFFICE/OUTPATIENT VISIT, NEW
I have researched this topic using Walkenbach's "Excel 2013: Power Programming with VBA" and a fair amount of web resources, including this awesome site, but have been unable to develop a fully-workable solution using VBA in Excel. The code for my current macro is:
Sub EasySplit()
Dim text As String
Dim a As Integer
Dim name As Variant
text = ActiveCell.Value
name = Split(text, "-", 2)
For a = 0 To 1
Cells(1, a + 3).Value = Trim(name(a))
Next a
End Sub
The code uses the "-" character as a delimiter to split the input string into two substrings (I have limited the output strings to 2, as there exists in some input strings multiple "-" characters). I have trimmed the second string output to remove leading spaces.
The trouble that I am having is that the output is being presented at the top of the activesheet, instead of on the activerow.
Thank you in advance for any help. I have been working on this for 2 days and although I have made some progress, I feel that I have reached an impasse. I think that the issue is somewhere in the
Cells(1, a + 3).Value = Trim(name(a))
code, specifically with "Cells()".
Thank you Conrad Frix!
Yah.. funny enough. Just after I post I have a brainstorm.. and modify the code to read:
Sub EasySplit()
Dim text As String
Dim a As Integer
Dim name As Variant
text = ActiveCell.Value
name = Split(text, "-", 2)
For a = 0 To 1
ActiveCell.Offset(0, 3 + a).Value = Trim(name(a))
Next a
End Sub
Not quite the colkumn1,column4 output that I want (it outputs to column3,column4), but it will work for my purpose.
Now I need to incorporate a loop so that the code runs on each successive cell in the column (downwards, step 1) skipping all bolded cells, until it hits an empty cell.
Modified answer to modified request.
This will start on row 1 and continue until a blank cell is found in column A. If you would like to start on a different row, perhaps row 2 if you have headers, change the
i = 1
line to
i = 2
I added a check on the upper bound of our variant before doing the output writes, in case the macro is run again on already formatted cells. (Does nothing instead of erroring out)
Sub EasySplit()
Dim initialText As String
Dim i As Double
Dim name As Variant
i = 1
Do While Trim(Cells(i, 1)) <> ""
If Not Cells(i, 1).Font.Bold Then
initialText = Cells(i, 1).text
name = Split(initialText, "-", 2)
If Not UBound(name) < 1 Then
Cells(i, 1) = Trim(name(0))
Cells(i, 4) = Trim(name(1))
End If
End If
i = i + 1
Loop
End Sub
just add a variable to keep track of the active row and then use that in place of the constant 1.
e.g.
Dim iRow as Integer = ActiveCell.Row
For a = 0 To 1
Cells(iRow , a + 3).Value = Trim(name(a))
Next a
Alternate method utilizing TextToColumns. This code also avoids using a loop, making it more efficient and much faster. Comments have been added to assist with understanding the code.
EDIT: I have expanded the code to make it more versatile by using a temp worksheet. You can then output the two columns to wherever you'd like. As stated in your original question, the output is now to columns 1 and 4.
Sub tgr()
Const DataCol As String = "A" 'Change to the correct column letter
Const HeaderRow As Long = 1 'Change to be the correct header row
Dim rngOriginal As Range 'Use this variable to capture your original data
'Capture the original data, starting in Data column and the header row + 1
Set rngOriginal = Range(DataCol & HeaderRow + 1, Cells(Rows.Count, DataCol).End(xlUp))
If rngOriginal.Row < HeaderRow + 1 Then Exit Sub 'No data
'We will be using a temp worksheet, and to avoid a prompt when we delete the temp worksheet we turn off alerts
'We also turn off screenupdating to prevent "screen flickering"
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'Move the original data to a temp worksheet to perform the split
'To avoid having leading/trailing spaces, replace all instances of " - " with simply "-"
'Lastly, move the split data to desired locations and remove the temp worksheet
With Sheets.Add.Range("A1").Resize(rngOriginal.Rows.Count)
.Value = rngOriginal.Value
.Replace " - ", "-"
.TextToColumns .Cells, xlDelimited, Other:=True, OtherChar:="-"
rngOriginal.Value = .Value
rngOriginal.Offset(, 3).Value = .Offset(, 1).Value
.Worksheet.Delete
End With
'Now that all operations have completed, turn alerts and screenupdating back on
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
You can do this in a single shot without looping using the VBA equivalent of entering this formula, then taking values only
as a formula
=IF(NOT(ISERROR(FIND("-",A1))),RIGHT(A1,LEN(A1)-FIND("-",A1)-1 ),A1)
code
Sub Quicker()
Dim rng1 As Range
Set rng1 = Range([a1], Cells(Rows.Count, "A").End(xlUp))
With rng1.Offset(0, 3)
.FormulaR1C1 = "=IF(NOT(ISERROR(FIND(""-"",RC[-3]))),RIGHT(RC[-3],LEN(RC[-3])-FIND(""-"",RC[-3])-1 ),RC[-3])"
.Value = .Value
End With
End Sub
I have a list of about 300 items, that I need spaced out every 8 cells as opposed to being one after the other. I'm sure there is an easy way to do this, however my brain is failing me. I have a feeling my terminology is hurting hence why I can't find an answer.
=IF(MOD(ROW()+7;8)=0;INDEX(A:A;INT(ROW()/8)+1);"")
Given that data begins at A1 and formula is used from row 1 (coulmn is not important).
Try below code
Sub Main()
Dim lastRow As Long
lastRow = Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To lastRow
If i = 1 Then
Cells(i, 5).Value = Cells(i, 1)
Else
Cells((i - 1) * 9, 5).Value = Cells(i, 1)
End If
Next
End Sub
Output
Can you please post a screen shot or add some additional detail?
Two things come to my mind for possible solutions:
1) Use Text to columns (if that is where you're going with this) or
2) Use a formula like =LEFT(A1, 10) in the 8th column and fill down (10 can be changed to whatever the first part of the string is that needs to be separated).
Provide some additional info and I'll take another look!
I need to hide a range of cells using a macro in excel. C11 contains the column index from where I need to start hiding the columns.
Sub test()
Dim i As Integer
Dim j As Integer
Dim rocket As Range
i = Range("c11").Value
j = 12
rocket = Range(Cells(5, i), Cells(5, j))
Range("Rocket").Select
Selection.EntireColumn.Hidden = True
End Sub
The code is giving some unexpected error and as I am a novice, so have no clue what needs to be done..
Tree steps to make your code working:
1st. Add Set key word in appropriate line which is necessary:
Set rocket = Range(Cells(5, i), Cells(5, j))
2nd. Rocket variable represents range, you will NOT need to call it in this way:
Range("Rocket")....
but
rocket....
3rd. Avoid Select method and Selection object always when possible. Therefore the last two lines replace with this single one (which implements 2nd step, too):
rocket.EntireColumn.Hidden = true
That last answer was awesome! Just for someone else's FYI, here is what worked in Excel 2007. The first line is always 3, but the ending line needed to be a variable. That's where I had the problem. THIS FIXED IT! The last 4 lines before the "End If" do the work. Hope this helps!
Dim RowsToHide As Range
Dim RowHideNum As Integer
' Set Correct Start Dates for Billing in New File
Workbooks("----- Combined_New_Students_Updated.xlsx").Activate
Sheets("2015").Activate
StartDateLine1 = Format(START_DATE_1, "ww") - 1 ' Convert Start Date to Week Number
StartDateLine1 = (StartDateLine1 * 6) - 2 ' Convert Start Date to Line Number
If StartDateLine1 >= "10" Then
Cells(4, "q").Value = ""
Cells(StartDateLine1, "q").Value = STATUS_1
Cells(StartDateLine1, "z").Value = "START DATE " + START_DATE_1
RowHideNum = StartDateLine1 - 2
Set RowsToHide = Range(Cells(3, "a"), Cells(RowHideNum, "ab"))
RowsToHide.Select
RowsToHide.EntireRow.Hidden = True
End If