I've written the code below but I can't get past a line where I want to insert a variable number of rows. The compiler screams that it needs a "list separator or )" where there is a colon. But I can't find other ways of writing this. Please, help! =)
So, the problematic line is denoted by two stars from each end. Just above it there is a commented line that I've also tried with no success.
Also, would you be so kind and explain me what I need the following commands for (they are also found in the problematic line):Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Finally, any suggestions of how I could improve the code, s.t., experienced programmers don't faint when they read it? =)
Huge thank you in advance,
Option Explicit
Dim ws As Worksheet
Dim Blatt1, Blatt2 As String
Dim Anfangsjahr1, Anfangsjahr2 As Integer
Dim reporting_Jahr1, reporting_Jahr2 As String
Public Sub Dreiecke()
For Each ws In Worksheets
If ws.Name Like "RVA_H*" Then
If IsEmpty(Blatt1) = False Then
Blatt2 = ws.Name
Anfangsjahr2 = ws.Range("A3").Value
reporting_Jahr2 = ws.Range("A1").Value
Else
Blatt1 = ws.Name
Anfangsjahr1 = ws.Cells(3, 1).Value
reporting_Jahr1 = ws.Cells(1, 1).Value
GoTo X
End If
Else: GoTo X
End If
If reporting_Jahr1 <> reporting_Jahr2 Then
MsgBox "Dreiecke von unterschiedlichen Jahren"
Exit Sub
ElseIf reporting_Jahr1 = reporting_Jahr2 Then
If Anfangsjahr1 < Anfangsjahr2 Then
'Sheets(Blatt2).Rows(3:3+Anfangsjahr2-Anfangsjahr1).EntireRow.Insert
**Worksheets(Blatt2).Rows(3: 3 + Anfangsjahr2 - Anfangsjahr1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove**
ElseIf Anfangsjahr1 > Anfangsjahr2 Then
Worksheets(Blatt1).Rows(3:3+Anfangsjahr1-Anfangsjahr2).Insert Shift:=xlDown
ElseIf Anfangsjahr1 = Anfangsjahr2 Then GoTo X
End If
End If
X: Next ws
End Sub
I don't follow exactly what you are trying to get to here but there are some syntax issues.
Not sure if this is what you want, but it fixes the syntax. Do you rally want
Worksheets(Blatt2).Rows("3:" & 3 + Anfangsjahr2 - Anfangsjahr1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
EDIT to expand on OP's question in the comments below
The double quotes are used to enclose a string. So normally when you are referencing rows you can say .Rows("3:9").Insert This is providing the rows you want to work with as a string.
In your case you wanted to dynamically provide last row so we have
our string "3:"
transition from string to variable &
and our variables and math 3 + Anfangsjahr2 - Anfangsjahr1
To make up .Rows("3:" & 3 + Anfangsjahr2 - Anfangsjahr1).Insert
You need to place the row number in double quotation marks and then concatenate the variables to the string using an ampersand:
Worksheets(Blatt2).Rows("3:" & 3 + Anfangsjahr2 - Anfangsjahr1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
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 have a file that has a bunch of Cells in the A column (1500) that look like this:
Perfect Imperfection;"Kevin Gates";"Luca Brasi 2: Gangsta Grillz";1
or
Perfect Imperfection;"Kevin Gates";"Luca Brasi 2: Gangsta Grillz";0
I am trying to delete cells that end in ;1
Note that some song titles have a 1 in them, and others take the form of:
Perfect Imperfection;;;1
I'm using the following code from a different Stack Overflow post that I have edited slightly:
Sub DeleteRowsWithX()
maxRow = ActiveSheet.UsedRange.Rows.Count
MsgBox (maxRow)
For i = 1 To maxRow
Do While (StrComp(ActiveSheet.Cells(i, 1).Text, ";1", vbTextCompare) = 0)
Rows(i).Select
Selection.Delete Shift:=xlUp
MsgBox ("Deleted")
Loop
Next
End Sub
If it helps, here are some examples of the file:
Perfect Imperfection;"Kevin Gates";"Luca Brasi 2: Gangsta Grillz";1
Perfect Strangers;"Lil Wayne";"Tha Carter V";1
Perplexing Pegasus;"Rae Sremmurd";;1
Phone Numbers Wiz Khalifa;;;0
Piano Man;"Billy Joel";;1
Picasso Baby Jay Z;;;0
Pick Up the Phone ft Young Thug Travis Scott;;;0
Picture;"Kid Rock";;1
Pillowtalk Conor Maynard;;;1
Pimp Juice;Nelly;Nellyville;1
Pinball Wizard;"The Who";;1
Pink Toes Childish Gambino;;;1
Which should look like:
Phone Numbers Wiz Khalifa;;;0
Picasso Baby Jay Z;;;0
Pick Up the Phone ft Young Thug Travis Scott;;;0
However, nothing is deleting. Can anybody advise? NOTE -- this not need to be done in VBA, I just want to delete rows that end in 1
Requirements: Delete entire row of values in column 1 that end with ";1"
For this kind of requirements suggest the use of AutoFilter and SpecialCells to delete all the target rows at once.
Try this:
Sub AutoFilter_To_DeleteRows()
With ActiveSheet
Application.Goto .Cells(1), 1
Rem Add a temporary header to avoid indiscriminate deletion of the first row.
.Cells(1).EntireRow.Insert
.Cells(1).Value2 = "Temporary Header"
Rem Filter values ending with ";1"
.Columns(1).AutoFilter Field:=1, Criteria1:="=*;1"
Rem Delete all resulting rows
.Columns(1).SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
End Sub
Keeping the answer close to the code that you have written.
You need to loop from the bottom of your list to the top. That way when rows are deleted, you do not skip rows. This can be done in your For loop by starting with the bottom of the list and moving backwards to the first row using Step -1.
The Right function can be used to test the last two characters of the cell value to see if they match to ;1.
The Do While can be removed.
The MsgBox's have been expanded to provide more detail when testing. They can be commented out once you are happy with the way the code is running.
Sub DeleteRowsWithX()
maxRow = ActiveSheet.UsedRange.Rows.Count
MsgBox "No. of Rows: " & maxRow
For i = maxRow To 1 Step -1
ValOfCell = ActiveSheet.Cells(i, 1).Value2
If Right(ValOfCell, 2) = ";1" Then
Rows(i).Delete Shift:=xlUp
MsgBox "Row: " & i & vbCrLf & "Value: " & ValOfCell & vbCrLf & "has been deleted."
End If
Next
End Sub
Jerry, I could not get StrComp to work the way I wanted, so I used Mid & Len to accomplish what you need. This will work since all the song titles end with ";?". Also, I did not add to the code, but consider doing everything you can to not use the Select method - this can lead to complications.
Sub DeleteRowsWithX()
Dim maxrow As Integer
Dim i As Integer
maxrow = ActiveSheet.UsedRange.Rows.Count
For i = 1 To maxrow
Do While Mid(Cells(i, 1).Text, Len(Cells(i, 1).Text) - 1, 2) = ";1"
Rows(i).Select
Selection.Delete Shift:=xlUp
MsgBox ("Deleted")
Loop
Next
End Sub
I have code creates new sheets naming them by their project numbers (e.g., PRJ_123456, PRJ_654654). The first chunk of code here works wonderfully. My problem is that some projects have 5 digits, instead of 6. In the second piece of code, when I pull the project number it causes problems for things I try to do. I have tried many ways of retaining the leading zero for five digit project numbers, but it does not do so when creating the spreadsheet.
Sub Pop()
Sheets("Project_Main").Select
Range("C2").Select
Do Until IsEmpty(ActiveCell)
If (Sheets("Program").Range("C3").Value) = ActiveCell.Value Then
Dim PRJNumber
PRJNumber = ActiveCell.Offset(0, 2)
'PRJNumber.NumberFormat = "000000"
MsgBox (PRJNumber)
Sheets("Template_PRJ").Select
Sheets("Template_PRJ").Copy Before:=Sheets(2)
Sheets("Template_PRJ (2)").Select
Dim SheetPRJName
SheetPRJName = "PRJ_" & PRJNumber
Sheets("Template_PRJ (2)").Name = SheetPRJName
end if
loop
end sub
This is what I try to do later
For Each wks In ActiveWorkbook.Worksheets
If ((Left(wks.Name, 3) = "PRJ")) Then
PRJNumber = Right(wks.Name, 6)
'MsgBox (prjNumber)
....
Make sure to DIM your PRJNumber variable as a string since that's what we are dealing with.
When the value comes through, if it's 5 characters instead of 6 append a 0. After you assign PRJNumber use: If len(PRJNumber) = 5 then PRJNumber = "0" & PRJNumber
Since you are appending "PRJ_" on the front of it for the sheet name, then should be good to go from here.
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 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