VBA code not working for a large number of iterations - vba

For some reason this macro freezes EXCEL when I set the for home = X to XX loop to more than 10 iterations.
This code downloads a webpage into excel, extracts cells that contain either 'overall' or 'carried' and copy them into another sheet in the same workbook.
Thank you
Sub Macro1()
'
' Macro1 Macro
'
'
Dim home As Integer
Dim Calc_sheet As Worksheet
Dim score_count As Integer
Dim inspection_count As Integer
Dim output_rows As Integer
Dim output_columns As Integer
Dim date_columns As Integer
'Counting variables
score_count = 3
inspection_count = 8
'Output rows and columns starting values
output_rows = 3
output_columns = 3
date_columns = 8
For home = 20 To 23
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;http://www.XXXXXXXX.org.uk/directory/" & Sheets("Output").Cells(home, 1), Destination:=Range("$A$1") _
)
'.CommandType = 0
.Name = "Homes"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
For x = 20 To 250
Select Case Left(Cells(x, 1), 7)
'Is it a score?
Case Is = "Overall"
Cells(x, 1).Copy
Sheets("Output").Select
Cells(output_rows, output_columns).Select
ActiveSheet.Paste
output_columns = output_columns + 1
'Is it a date?
Case Is = "Carried"
Cells(x, 1).Copy
Sheets("Output").Select
Cells(output_rows, date_columns).Select
ActiveSheet.Paste
date_columns = date_columns + 1
Case Else
End Select
Sheets("Calc_sheet").Activate
Cells(x, 1).Activate
Next x
'Clean sheet
ActiveSheet.Cells.Delete
'Go back to top
Range("A1").Select
'Reset column count
output_columns = 3
date_columns = 8
output_rows = output_rows + 1
Next home
End Sub

I updated the code, try it again!
Try replacing your inner-loop with this one :
Dim wsC As Worksheet
Dim wsO As Worksheet
Set wsC = Worksheets("Calc_sheet")
Set wsO = Worksheets("Output")
For x = 20 To 250
yourContent = wsC.Cells(x, 1)
yourCase = Left(yourContent, 7)
Select Case yourCase
'Is it a score?
Case Is = "Overall"
wsO.Cells(output_rows, output_columns) = yourContent
output_columns = output_columns + 1
'Is it a date?
Case Is = "Carried"
wsO.Cells(output_rows, date_columns) = yourContent
date_columns = date_columns + 1
Case Else
End Select
Next x

Related

How to Copy and Paste in First Empty Cell and End when Fulfilled

I have a spreadsheet of products, which are in particular fonts and backgrounds. I am trying to create a macro so when I perform the find function (CLTR-F), I can click a macro button which will copy my selection, and paste it into the first available cell in Row N starting with the second row ("N2") and ending with the 12th row ("N12").
I have more data in N, for example in N13 and N14, so I cannot simply count the rows occupied and add one. I want to make this code work so this process exits once the first cell has been pasted into. Currently my code simply pastes the selected cell into both N2 and N3. The goal is that once the value is pasted, the process ends. But if the value is not pasted, it will go onto the next available cell and paste, and end, and so on if the cells are occupied until it is pasted in the first empty cell. Below is what I have, and so far it pastes into both N2 and N3, (If N2 is not occupied.)
Sub CopyPasteFirstEmptyCell()
'Copy the selection
Selection.Copy
'Test for N2
If IsEmpty(Range("N2")) = True Then
Selection.Copy Range("N2")
End If
'Test for N3
If IsEmpty(Range("N2")) = True Then
Selection.Copy Range("N3")
'Test For N4-N12 etc. etc.
End Sub
Thank you so kindly for listening. I have looked at relevant threads and have not found a sufficient answer of yet, and I apologize if that answer already exists openly.
I created variables and added them to a final variable to decide the range.
Sub Copy()
'Copy the selection
Selection.Copy
'Create variables
Dim intN2 As Integer
Dim intN3 As Integer
Dim intN4 As Integer
Dim intN5 As Integer
Dim intN6 As Integer
Dim intN7 As Integer
Dim intN8 As Integer
Dim intN9 As Integer
Dim intN10 As Integer
Dim intN11 As Integer
Dim intN12 As Integer
Dim finalint As Integer
'Create If Then statements to increaes finalint
'For N2
If IsEmpty(Range("N2")) = True Then
intN2 = 0
ElseIf IsEmpty(Range("N2")) = False Then
intN2 = 1
End If
'For N3
If IsEmpty(Range("N3")) = True Then
intN3 = 0
ElseIf IsEmpty(Range("N3")) = False Then
intN3 = 1
End If
'For N4
If IsEmpty(Range("N4")) = True Then
intN4 = 0
ElseIf IsEmpty(Range("N4")) = False Then
intN4 = 1
End If
'For N5
If IsEmpty(Range("N5")) = True Then
intN5 = 0
ElseIf IsEmpty(Range("N5")) = False Then
intN5 = 1
End If
'For N6
If IsEmpty(Range("N6")) = True Then
intN6 = 0
ElseIf IsEmpty(Range("N6")) = False Then
intN6 = 1
End If
'For N7
If IsEmpty(Range("N7")) = True Then
intN7 = 0
ElseIf IsEmpty(Range("N7")) = False Then
intN7 = 1
End If
'For N8
If IsEmpty(Range("N8")) = True Then
intN8 = 0
ElseIf IsEmpty(Range("N8")) = False Then
intN8 = 1
End If
'For N9
If IsEmpty(Range("N9")) = True Then
intN9 = 0
ElseIf IsEmpty(Range("N9")) = False Then
intN9 = 1
End If
'For N10
If IsEmpty(Range("N10")) = True Then
intN10 = 0
ElseIf IsEmpty(Range("N10")) = False Then
intN10 = 1
End If
'For N11
If IsEmpty(Range("N11")) = True Then
intN11 = 0
ElseIf IsEmpty(Range("N11")) = False Then
intN11 = 1
End If
'For N12
If IsEmpty(Range("N12")) = True Then
intN12 = 0
ElseIf IsEmpty(Range("N12")) = False Then
intN12 = 1
End If
'Make finalint the total of all other integers
finalint = intN2 + intN3 + intN4 + intN5 + intN6 + intN7 + intN8 + intN9 + intN10 + intN11 + intN12
'Place selection depending on amount of finalint
If finalint = 0 Then
Selection.Copy Range("N2")
ElseIf finalint = 1 Then
Selection.Copy Range("N3")
ElseIf finalint = 2 Then
Selection.Copy Range("N4")
ElseIf finalint = 3 Then
Selection.Copy Range("N5")
ElseIf finalint = 4 Then
Selection.Copy Range("N6")
ElseIf finalint = 5 Then
Selection.Copy Range("N7")
ElseIf finalint = 6 Then
Selection.Copy Range("N8")
ElseIf finalint = 7 Then
Selection.Copy Range("N9")
ElseIf finalint = 8 Then
Selection.Copy Range("N10")
ElseIf finalint = 9 Then
Selection.Copy Range("N11")
ElseIf finalint = 10 Then
Selection.Copy Range("N12")
End If
End Sub

Excel VBA Macro - Out of Memory Error

I am having trouble when running a macro whereby I get an error, usually at the end, stating that it "Out of memory".
I've looked over a number of posts and followed recommendations to clear any variables and ensure that the code is "cleaner". However, the error still persists.
I have included the code below, any feedback would be greatly appreciated.
A summary of the purpose:
User clicks a button in a template (which is where the code resides)
Macro 1 cleans up the data that the user pastes into a template page.
A userform will appear after macro 1 which the user must input some data - customer name, contract numbers, etc.
Macro 2 runs when the userform button is submitted which creates a new workbook containing all the data from the template (formatted in macro1) and the data from the form.
It then formats the data for printing with a logo, etc.
Macro 1
Private Sub ContractsClean()
Application.Visible = True
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.CutCopyMode = False
Sheets("Paste").Name = "Data"
Sheets("Data").Columns("A:B").EntireColumn.Delete
Dim x As Long, lastrow As Long
lastrow = Sheets("Data").Cells(Rows.Count, "A").End(xlUp).Row
'Clean the codes
For x = lastrow To 2 Step -1
If Len(Sheets("Data").Cells(x, 1)) > 9 Then
Sheets("Data").Cells(x, 1).Value = Right(Sheets("Data").Cells(x, 1).Value, 9)
End If
Next x
'Add the leading zero
Sheets("Data").Select
Range("A:A").Select
Dim Rng As Range
Dim bChanged As Boolean
Dim icol As Long
Dim sString As String
Dim iWSs As Long
iWSs = Workbooks.Count
If iWSs >= 1 Then
icol = Selection.Column
lastrow = Cells(Rows.Count, icol).End(xlUp).Row
For Each Rng In Selection
If TypeName(Rng.Value) = "Double" Then
If Left(Rng.Value, 1) = "9" Then
Rng = "'0" & Rng.Value
bChanged = True
End If
End If
If TypeName(Rng.Value) = "String" Then
If Left(Rng.Value, 3) = "09-" Then
sString = Rng.Value
sString = "'" & Replace(sString, "-", "")
Rng.Value = sString
bChanged = True
End If
End If
If Rng.Errors(xlNumberAsText).Value = True And bChanged = True Then Rng.Errors(xlNumberAsText).Ignore = True
If Rng.Row = lastrow Then Exit For
Next Rng
End If
If iWSs >= 1 Then
icol = Selection.Column
lastrow = Cells(Rows.Count, icol).End(xlUp).Row
For Each Rng In Selection
If TypeName(Rng.Value) = "Double" Then
If Left(Rng.Value, 1) = "8" Then
Rng = "'0" & Rng.Value
bChanged = True
End If
End If
If TypeName(Rng.Value) = "String" Then
If Left(Rng.Value, 3) = "08-" Then
sString = Rng.Value
sString = "'" & Replace(sString, "-", "")
Rng.Value = sString
bChanged = True
End If
End If
If Rng.Errors(xlNumberAsText).Value = True And bChanged = True Then Rng.Errors(xlNumberAsText).Ignore = True
If Rng.Row = lastrow Then Exit For
Next Rng
End If
Rng = Empty
bChanged = Empty
icol = Empty
sString = Empty
iWSs = Empty
Sheets("Data").Columns("B").EntireColumn.Delete
Sheets("Data").Range("C1").Value = "Quantity"
Sheets("Data").Columns("D").EntireColumn.Delete
Sheets("Data").Columns("E").EntireColumn.Delete
Sheets("Data").Range("E:F").NumberFormat = "dd/mm/yyyy"
Dim ws As Worksheet
Set ws = Sheets("Data")
ws.Range("A:B").Locked = False
ws.Range("C:D").Locked = True
ws.Range("E:F").Locked = False
ws.Protect DrawingObjects:=True, Contents:=True, Scenarios:= _
True, AllowDeletingRows:=True, AllowFormattingCells:=True, AllowFiltering:=True, AllowInsertingRows:=True, Password:="Sanchez7"
'Completion message box
Dim Answer As String
Dim MyNote As String
'Place your text here
MyNote = "Cleanse complete. Do you want to create a local price agreement?"
'Display MessageBox
Answer = MsgBox(MyNote, vbQuestion + vbYesNo, "Action")
If Answer = vbNo Then
'Code for No button Press
Else
'Code for Yes button Press
ProposalForm.Show
End If
Answer = Empty
MyNote = Empty
lastrow = Empty
End Sub
Form Code
Private Sub CommandButton1_Click()
Dim sBuyGroup As String, sLPA As String, sRep As String, sStart As Date, sEnd As Date, sCurrency As String
Dim bExit As Boolean, sSort As String
sBuyGroup = txt_BuyGroup.Text
sLPA = txt_LPA.Text
sRep = txt_Rep.Text
sStart = txt_Start.Text
sEnd = txt_End.Text
sCurrency = ComboBox1.Value
If sBuyGroup = "" Then
bExit = True
MsgBox ("The account number cannot be blank")
End If
If sLPA = "" And bExit = False Then
bExit = True
MsgBox ("The carriage option cannot be blank")
End If
If sRep = "" And bExit = False Then
bExit = True
MsgBox ("The discount option cannot be blank")
End If
If bExit = False Then
Call CreateProposal(sBuyGroup, sLPA, sRep, sStart, sEnd, sCurrency)
Unload Me
Else
End If
sBuyGroup = Empty
sLPA = Empty
sRep = Empty
sStart = Empty
sEnd = Empty
sCurrency = Empty
End Sub
Macro 3 (which I believe is what causes the error)
Sub CreateProposal(sBuyGroup As String, sLPA As String, sRep As String, sStart As Date, sEnd As Date, sCurrency As String)
Dim picLogo As Picture
Set picLogo = Sheets("Info").Pictures("PH_LOGO")
'Copy data from original workbook
Dim exApp As Excel.Application
Set exApp = GetExcelObject()
exApp.Visible = True
Dim OGWB As Workbook
Set OGWB = ActiveWorkbook
OGWB.Sheets("Data").Range("A1:F15000").Copy
Dim wbProposal As Workbook
Set wbProposal = exApp.Workbooks.Add
wbProposal.Activate
wbProposal.Sheets("Sheet1").Range("A1").PasteSpecial xlPasteValues
wbProposal.Sheets("Sheet1").Name = "Raw"
exApp.CutCopyMode = False
exApp.Application.ScreenUpdating = False
'Copy the logo so we can close original workbook
wbProposal.Sheets.Add
wbProposal.Sheets("Sheet2").Name = "LPA"
OGWB.Sheets("Info").Pictures("PH_LOGO").Cut
wbProposal.Sheets("LPA").Paste
Selection.Name = "PH_LOGO"
wbProposal.Sheets("LPA").Pictures("PH_LOGO").Left = 20
wbProposal.Sheets("LPA").Pictures("PH_LOGO").Top = 13
'wbProposal.Sheets("LPA").Pictures("PH_LOGO").Width = Application.CentimetersToPoints(5.51)
'wbProposal.Sheets("LPA").Pictures("PH_LOGO").Height = Application.CentimetersToPoints(1.64)
wbProposal.Sheets("LPA").Range("A1").Select
Set picLogo = Nothing
exApp.CutCopyMode = False
wbProposal.Activate
wbProposal.Sheets("LPA").Select
'Set BG to all white
With wbProposal.Sheets("LPA").Cells.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
.PatternTintAndShade = 0
End With
'Add contact header
wbProposal.Sheets("LPA").Range("D2").Value = "performancehealth.co.uk"
wbProposal.Sheets("LPA").Range("D3").Value = "Main: +44 (0) 3448 730 035"
wbProposal.Sheets("LPA").Range("D4").Value = "Fax: +44 (0) 1623 557 769"
wbProposal.Sheets("LPA").Range("G2").Value = "Nunn Brook Road, Huthwaite,"
wbProposal.Sheets("LPA").Range("G3").Value = "Sutton-in-Ashfield"
wbProposal.Sheets("LPA").Range("G4").Value = "Nottinghamshire, NG17 2HU, UK"
With wbProposal.Sheets("LPA").Range("D2").Font
.ThemeColor = xlThemeColorAccent1
.TintAndShade = 0
.Bold = True
End With
With wbProposal.Sheets("LPA").Range("D3:D4,G2:G4").Font
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0.499984740745262
End With
wbProposal.Sheets("LPA").Range("G6").Value = "Local Price Agreement"
With wbProposal.Sheets("LPA").Range("G6").Font
.ThemeColor = xlThemeColorAccent1
.TintAndShade = 0
.Bold = True
.Size = 14
End With
'Arrange Column widths
wbProposal.Sheets("LPA").Columns("A").ColumnWidth = 2.5
wbProposal.Sheets("LPA").Columns("B").ColumnWidth = 13
wbProposal.Sheets("LPA").Range("B14").Value = "Item Code"
wbProposal.Sheets("LPA").Columns("C").ColumnWidth = 41.5
wbProposal.Sheets("LPA").Range("C14").Value = "Item Description"
wbProposal.Sheets("LPA").Columns("D:F").ColumnWidth = 12
wbProposal.Sheets("LPA").Range("D14").Value = "Sale UOM"
wbProposal.Sheets("LPA").Range("E14").Value = "Min Qty"
wbProposal.Sheets("LPA").Range("F14").Value = "Rate"
wbProposal.Sheets("LPA").Columns("G:H").ColumnWidth = 13.5
wbProposal.Sheets("LPA").Range("G14").Value = "Start Date"
wbProposal.Sheets("LPA").Range("H14").Value = "Expiry Date"
wbProposal.Sheets("LPA").Range("B14:H14").Font.Bold = True
With wbProposal.Sheets("LPA").Range("B14:H14").Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = -4.99893185216834E-02
.PatternTintAndShade = 0
End With
'Fill out details from form
wbProposal.Sheets("LPA").Range("B8").Value = "Buying Group:"
wbProposal.Sheets("LPA").Range("B10").Value = "Sales Rep:"
wbProposal.Sheets("LPA").Range("B11").Value = "Currency:"
wbProposal.Sheets("LPA").Range("E8").Value = "LPA Number:"
wbProposal.Sheets("LPA").Range("E10").Value = "Start Date:"
wbProposal.Sheets("LPA").Range("E11").Value = "Expiry Date:"
wbProposal.Sheets("LPA").Range("B8:B11").Font.Bold = True
wbProposal.Sheets("LPA").Range("E8:E11").Font.Bold = True
wbProposal.Sheets("LPA").Range("C8").Value = sBuyGroup
wbProposal.Sheets("LPA").Range("C10").Value = sRep
wbProposal.Sheets("LPA").Range("C11").Value = sCurrency
wbProposal.Sheets("LPA").Range("F8").Value = sLPA
wbProposal.Sheets("LPA").Range("F10").Value = sStart
wbProposal.Sheets("LPA").Range("F11").Value = sEnd
sBuyGroup = Empty
sRep = Empty
sCurrency = Empty
sLPA = Empty
sStart = Empty
sEnd = Empty
'Import the list
Dim lastrow As Long
wbProposal.Sheets("Raw").Select
lastrow = wbProposal.Sheets("Raw").Cells(Rows.Count, "A").End(xlUp).Row
wbProposal.Sheets("Raw").Columns("C").Insert Shift:=xlToRight
wbProposal.Sheets("Raw").Range("F:G").NumberFormat = "dd/mm/yyyy"
wbProposal.Sheets("Raw").Range("E" & lastrow).NumberFormat = "£#,##0.00"
wbProposal.Sheets("Raw").Range("A2:G" & lastrow).Copy
wbProposal.Sheets("LPA").Select
wbProposal.Sheets("LPA").Range("B15").PasteSpecial xlPasteValuesAndNumberFormats
exApp.CutCopyMode = False
'Setup print area
lastrow = wbProposal.Sheets("LPA").Cells(Rows.Count, "B").End(xlUp).Row
wbProposal.Sheets("LPA").Range("F15:F" & lastrow).NumberFormat = "£#,##0.00"
wbProposal.Sheets("LPA").PageSetup.PrintArea = "$A$1:$H$" & lastrow
With wbProposal.Sheets("LPA").PageSetup
.PrintTitleRows = "$14:$14"
.PrintTitleColumns = ""
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 100
End With
'Redo the picture size (changes during column amendments
'wbProposal.Sheets("LPA").Pictures("PH_LOGO").Width = Application.CentimetersToPoints(5.51)
'wbProposal.Sheets("LPA").Pictures("PH_LOGO").Height = Application.CentimetersToPoints(1.64)
lastrow = Empty
exApp.DisplayAlerts = False
exApp.CutCopyMode = False
wbProposal.Sheets("LPA").Range("A1").Select
wbProposal.Sheets("Raw").Delete
exApp.DisplayAlerts = False
exApp.ScreenUpdating = True
OGWB.Close False
Set OGWB = Nothing
Set wbProposal = Nothing
Set exApp = Nothing
Application.Quit
End Sub
'-----------------------------------------------------------------------------
' Return an intance of Excel
' First tries to open an existing instance. If it fails, it will create an instance.
' If that fails too, then we return 'Nothing'
'-----------------------------------------------------------------------------
Public Function GetExcelObject() As Object
On Error Resume Next
Dim xlo As Object
' Try to get running instance of Excel
Set xlo = GetObject("Excel.Application")
If xlo Is Nothing Then
Set xlo = CreateObject("Excel.Application")
End If
Set GetExcelObject = xlo
End Function

Slow macro hiding rows based on value

I have a table that I want to completely hide or hide/show rows within the table, depending on whether a cell value is 0 or above.
It looks for a value of 0 within cell D26; if 0 it hides rows 24-51, if not 0 it hides/shows rows depending on whether there is a value in the C column between rows 34 and 49.
The macro below is too slow to be a viable option. Can anyone suggest an alternative way of doing this, that might work in a few seconds rather than a few minutes? I think it's because I'm running the For/If/Else loop.
Sub HideManifolds()
'
' HideManifolds Macro
'
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
ChkCol = 3
Manifold1BeginTableRow = 34
Manifold1EndTableRow = 49
Manifold1BeginRow = 24
Manifold1EndRow = 51
For Manifold1RowCnt = Manifold1BeginRow To Manifold1EndRow
If Cells(26, 4).Value = 0 Then
Cells(Manifold1RowCnt, 1).EntireRow.Hidden = True
Else
For Manifold1TableRowCnt = Manifold1BeginTableRow To Manifold1EndTableRow
If Cells(Manifold1TableRowCnt, ChkCol).Value = 0 Then
Cells(Manifold1TableRowCnt, ChkCol).EntireRow.Hidden = True
Else
Cells(Manifold1TableRowCnt, ChkCol).EntireRow.Hidden = False
End If
Next Manifold1TableRowCnt
End If
Next Manifold1RowCnt
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
'
End Sub
I think you don't need this loop For Manifold1RowCnt = Manifold1BeginRow To Manifold1EndRow
code:
Sub HideManifolds()
'
' HideManifolds Macro
'
Dim hRng As Range, vRng As Range
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
ChkCol = 3
Manifold1BeginTableRow = 34
Manifold1EndTableRow = 49
Manifold1BeginRow = 24
Manifold1EndRow = 51
If Cells(26, 4).Value = 0 Then
Rows(Manifold1BeginRow & ":" & Manifold1EndRow).Hidden = True
Else
For Manifold1TableRowCnt = Manifold1BeginTableRow To Manifold1EndTableRow
If Cells(Manifold1TableRowCnt, ChkCol).Value = 0 Then
If hRng Is Nothing Then
Set hRng = Cells(Manifold1TableRowCnt, ChkCol)
Else
Set hRng = Union(hRng, Cells(Manifold1TableRowCnt, ChkCol))
End If
Else
If vRng Is Nothing Then
Set vRng = Cells(Manifold1TableRowCnt, ChkCol)
Else
Set vRng = Union(vRng, Cells(Manifold1TableRowCnt, ChkCol))
End If
End If
Next Manifold1TableRowCnt
If Not hRng Is Nothing Then hRng.EntireRow.Hidden = True
If Not vRng Is Nothing Then vRng.EntireRow.Hidden = False
End If
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
'
End Sub

Repeating merged cell range

I have the following basic script that merges cells with the same value in Column R
Sub MergeCells()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim rngMerge As Range, cell As Range
Set rngMerge = Range("R1:R1000")
MergeAgain:
For Each cell In rngMerge
If cell.Value = cell.Offset(1, 0).Value And IsEmpty(cell) = False Then
Range(cell, cell.Offset(1, 0)).Merge
GoTo MergeAgain
End If
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
What I would like to do is repeat this in columns A:Q and S:T but, I would like these columns to be merged in the same merged cell ranges as column R, i.e. if R2:R23 is merged then A2:A23, B2:B23, C2:C23 etc. will also be merge.
Columns A:Q do not contain values, column S:T have values but, these will be the same values throughout the range.
Any ideas
Apols for the earlier edit - this now deals with more than one duplicate in col R.
Note that this approach will work on the current (active) sheet.
Sub MergeCells()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim cval As Variant
Dim currcell As Range
Dim mergeRowStart As Long, mergeRowEnd As Long, mergeCol As Long
mergeRowStart = 1
mergeRowEnd = 1000
mergeCol = 18 'Col R
For c = mergeRowStart To mergeRowEnd
Set currcell = Cells(c, mergeCol)
If currcell.Value = currcell.Offset(1, 0).Value And IsEmpty(currcell) = False Then
cval = currcell.Value
strow = currcell.Row
endrow = strow + 1
Do While cval = currcell.Offset(endrow - strow, 0).Value And Not IsEmpty(currcell)
endrow = endrow + 1
c = c + 1
Loop
If endrow > strow+1 Then
Call mergeOtherCells(strow, endrow)
End If
End If
Next c
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Sub mergeOtherCells(strw, enrw)
'Cols A to T
For col = 1 To 20
Range(Cells(strw, col), Cells(enrw, col)).Merge
Next col
End Sub
You can try the below code as well. It would require you to put a 'No' after the last line in column R (R1001) so as to end the while loop.
Sub Macro1()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
flag = False
k = 1
While ActiveSheet.Cells(k, 18).Value <> "No"
i = 1
j = 0
While i < 1000
rowid = k
If Cells(rowid, 18).Value = Cells(rowid + i, 18).Value Then
j = j + 1
flag = True
Else
i = 1000
End If
i = i + 1
Wend
If flag = True Then
x = 1
While x < 21
Range(Cells(rowid, x), Cells(rowid + j, x)).Merge
x = x + 1
Wend
flag = False
k = k + j
End If
k = k + 1
Wend
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

Using a loop in Excel/VBS to populate a form

Please can somebody help me with the correct DIM statements and syntax to simplify the following into a DO UNTIL loop?:
Sub DesRisk_Loader()
Dim Qn(7) As String
Dim Ys(7) As String
Dim No(7) As String
Dim Wk(7) As Integer
Application.ScreenUpdating = False
n = 1
x = 1
Do
Application.Goto Reference:="DesHome"
ActiveCell.Offset(x, 0).Select
Qn(n) = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
Ys(n) = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
No(n) = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
Wk(n) = ActiveCell.Value
x = x + 2
n = n + 1
Loop Until n = 8
''Q.1
If Qn(1) <> "" Then
DesForm.DesFrame1.Visible = True
DesForm.Dq1.Caption = Qn(1)
FH = 0
If Ys(1) = "P" Then
DesForm.D1y.Value = True
Else
DesForm.D1y.Value = False
End If
If No(1) = "O" Then
DesForm.D1n.Value = True
Else
DesForm.D1n.Value = False
End If
DesForm.DesDly1.Value = Wk(1)
Else:
Exit Sub
End If
''Q.2
If Qn(2) <> "" Then
DesForm.DesFrame2.Visible = True
DesForm.Dq2.Caption = Qn(2)
FH = 1
If Ys(2) = "P" Then
DesForm.D2y.Value = True
Else
DesForm.D2y.Value = False
End If
If No(2) = "O" Then
DesForm.D2n.Value = True
Else
DesForm.D2n.Value = False
End If
DesForm.DesDly2.Value = Wk(2)
Else: GoTo Jump1
End If
''Q.3
If Qn(3) <> "" Then
DesForm.DesFrame3.Visible = True
DesForm.Dq3.Caption = Qn(3)
FH = 2
If Ys(3) = "P" Then
DesForm.D3y.Value = True
Else
DesForm.D3y.Value = False
End If
If No(3) = "O" Then
DesForm.D3n.Value = True
Else
DesForm.D3n.Value = False
End If
DesForm.DesDly3.Value = Wk(3)
Else: GoTo Jump1
End If
ditto till..
''Q.7
If Qn(7) <> "" Then
DesForm.DesFrame7.Visible = True
DesForm.Dq7.Caption = Qn(7)
FH = 6
If Ys(7) = "P" Then
DesForm.D7y.Value = True
Else
DesForm.D7y.Value = False
End If
If No(7) = "O" Then
DesForm.D7n.Value = True
Else
DesForm.D7n.Value = False
End If
DesForm.DesDly7.Value = Wk(7)
Else: GoTo Jump1
End If
Jump1:
DesForm.Height = 140 + (FH * 75)
DesForm.DesOK.Top = 85 + (FH * 75)
DesForm.DesCancel.Top = 85 + (FH * 75)
Load DesForm
DesForm.Show
End Sub
Thanks
Scott
At the top of your code (First Line in the entire module), type the following OPTION EXPLICIT
That will help identify all undeclared variables.