I'm making a VBA program that changes the visuals of the excel file. There are some tags ("BN", "A", "C" etc.) which say how the rows/cells should be changed.
For example: the tag "A" means - set the cell font to "Arial", size 13... etc.
The program was working until I made some changes a while ago. Since then it's giving me always an runtime error. Has anyone any clue as to why?
The code:
Option Explicit
Sub macro1()
Dim rowIndex As Integer
Dim lastRowIndex As Integer
Dim offset As Integer
lastRowIndex = 2700
With ActiveSheet
For rowIndex = 1 To 3
Rows(1).EntireRow.Delete
Next rowIndex
With Cells.Font
.Name = "Arial"
.Size = 8
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Bold = False
.Underline = xlUnderlineStyleNone
.ColorIndex = 1
End With
With Cells
.RowHeight = 11
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Columns(1).ColumnWidth = 13.5
Columns(2).ColumnWidth = 60
With Columns(3)
.HorizontalAlignment = xlCenter
.ColumnWidth = 5.5
End With
With Columns(4)
.HorizontalAlignment = xlRight
.ColumnWidth = 6.5
End With
With Columns(5)
.HorizontalAlignment = xlRight
.ColumnWidth = 6.5
End With
Columns(4).HorizontalAlignment = xlRight
Columns(5).HorizontalAlignment = xlRight
rowIndex = 1
offset = 0
Do While (rowIndex - offset) < lastRowIndex
If Cells(rowIndex, 5).Value = "A" Or Cells(rowIndex, 5).Value = "NAZOV" Or _
Cells(rowIndex, 5).Value = "C" Or Cells(rowIndex, 6).Value = "BN" Then
If Cells(rowIndex, 5).Value = "A" Then
Cells(rowIndex, 5).ClearContents
With Cells(rowIndex, 2).Font
.Name = "Arial Narrow"
.Size = 11
.Bold = True
.Color = RGB(204, 0, 0)
End With
With Cells(rowIndex, 2)
.RowHeight = 16
.HorizontalAlignment = xlCenter
End With
End If
If Cells(rowIndex, 5).Value = "NAZOV" Then
Cells(rowIndex, 5).ClearContents
With Cells(rowIndex, 2).Font
.Name = "Arial"
.Size = 9
.Bold = True
.Underline = xlUnderlineStyleSingle
.Color = RGB(0, 0, 153)
End With
With Cells(rowIndex, 2)
.RowHeight = 13
End With
End If
If Cells(rowIndex, 5).Value = "C" Then
Cells(rowIndex, 5).ClearContents
Cells(rowIndex, 6).ClearContents
Cells(rowIndex, 7).ClearContents
With Cells(rowIndex, 2).Font
.Name = "Arial Narrow"
.Size = 8
.Italic = True
.ColorIndex = 16
End With
With Cells(rowIndex, 2)
.RowHeight = 12
End With
End If
If Cells(rowIndex, 6) = "BN" Then
Cells(rowIndex, 6).ClearContents
If (Cells(rowIndex + 1, 5) <> "C") Then
Rows(rowIndex + 1).Insert
With Rows(rowIndex + 1)
.RowHeight = 3
.Font.Size = 2
End With
offset = offset + 1
Else
Rows(rowIndex + 2).Insert
With Rows(rowIndex + 2)
.RowHeight = 3
.Font.Size = 2
End With
offset = offset + 2
End If
End If
Else
Cells(rowIndex, 2).WrapText = True
Rows(rowIndex).AutoFit
End If
If Cells(rowIndex, 6).Value = "D" Then
Cells(rowIndex, 6).ClearContents
With Selection.Font
.Underline = xlUnderlineStyleSingle
.Bold = True
.Italic = False
End With
End If
If Cells(rowIndex, 6).Value = "E" Then
With Selection.Font
.Underline = xlUnderlineStyleSingle
.Bold = False
End With
End If
If Cells(rowIndex, 5).Value = "P" Then
Cells(rowIndex, 5).ClearContens
End If
If ( _
((Cells(rowIndex, 5) = Cells(rowIndex - 1, 5)) Or (Cells(rowIndex, 5) = Cells(rowIndex - 2, 5))) And _
((Cells(rowIndex, 4) = "" And Cells(rowIndex - 1, 4) <> "") Or (InStr(Cells(rowIndex, 2).Text, ">"))) And _
(Cells(rowIndex - 1, 2).Font.Size = 9) Or (Cells(rowIndex, 2).Font.Size = 9 And Cells(rowIndex - 1, 2).Font.Size = 9)) Then
With Cells(rowIndex, 2).Font
.Italic = True
.ColorIndex = 16
.Bold = False
.Size = 8
.Underline = False
End With
Cells(rowIndex, 2).WrapText = True
Rows(rowIndex).AutoFit
End If
rowIndex = rowIndex + 1
Loop
End With
End Sub
The runtime error appears on the last IF statement:
If ( _
((Cells(rowIndex, 5) = Cells(rowIndex - 1, 5)) Or (Cells(rowIndex, 5) = Cells(rowIndex - 2, 5))) And _
((Cells(rowIndex, 4) = "" And Cells(rowIndex - 1, 4) <> "") Or (InStr(Cells(rowIndex, 2).Text, ">"))) And _
(Cells(rowIndex - 1, 2).Font.Size = 9) Or (Cells(rowIndex, 2).Font.Size = 9 And Cells(rowIndex - 1, 2).Font.Size = 9)) Then
Related
An agency I am working with just recently upgraded to Windows 10 and also upgraded from Office 2010 to 2016. All machines have the same image This agency exports reports from SSRS into an Excel document. We have an in house macro that automatically edits and formats the report for publication. For some reason when the same excel document with the same report and formatted table is opened on a different computer, the column widths very. The column widths are set via hard coded values in the macro. This affects the presentation of their final publication and, although it is just barely off, it is unacceptable to their clients.
I have explored a few different possibilities. I first looked at the font and its size after the document was opened on the different machine. They are both the same. I then looked to see if resolution may play a role. Although changing the DPI settings appeared to change the column width values, the DPI settings are the same on all the machines. If the macro is run again on the same report the column widths turn out correctly.
I'm really not sure what else to check. Could someone give me some advice or point me in the right direction?
Sub FormatAppDeptLvl()
'Macro to format Long Bill Department Level report
Dim wsSheet As Worksheet
Dim lastRow As Integer
Dim lastCol As Integer
Dim i As Integer, j As Integer, k As Integer, m As Integer, n As Integer, p As Integer, q As Integer
Dim checktotal As String
'Sheets.Add
Application.DisplayAlerts = False
On Error Resume Next
Set wsSheet = Sheets("NewReport")
On Error GoTo 0
If Not wsSheet Is Nothing Then
'Sheet1 exists
Sheets("NewReport").Delete
Sheets.Add().Name = "NewReport"
Else
'Sheet1 does not exist
Sheets.Add().Name = "NewReport"
End If
Sheets("CLMAppropDept").Select
With ActiveSheet
lastRow = .Cells(.Rows.Count, "F").End(xlUp).Row
End With
With ActiveSheet
lastCol = .Cells(lastRow, .Columns.Count).End(xlToLeft).Column
End With
Range(Cells(1, 1), Cells(lastRow, lastCol)).Select
Selection.Copy
'To unHighlight cells
Cells(1, 1).Select
Sheets("NewReport").Select
Range("A1").Select
ActiveSheet.Paste
ActiveSheet.Unprotect
Range(Cells(1, 1), Cells(lastRow, lastCol)).Select
Selection.Locked = False
Selection.FormulaHidden = True
Call ColorTabs
'Calculate last row and column
lastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
lastCol = ActiveSheet.Cells(lastRow, ActiveSheet.Columns.Count).End(xlToLeft).Column
'Merge Title
Range(Cells(1, 1), Cells(1, lastCol)).Select
Selection.Merge
'Range("B1:G1").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlLTR
.MergeCells = True
End With
'Table dimensions : Rows Height
ActiveSheet.Rows.RowHeight = 10
Range(Cells(1, 1), Cells(1, lastCol)).RowHeight = 12
Range(Cells(2, 1), Cells(2, lastCol)).RowHeight = 18
Range(Cells(3, 1), Cells(lastRow, 1)).RowHeight = 10
'Table dimensions : Column Width
ActiveSheet.Columns.ColumnWidth = 11.86
Range("A:A").ColumnWidth = 29.075
'Table dimensions : Column Width
lastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
For k = 2 To lastCol
checkfund = Cells(2, k).Value
If checkfund Like "TOTAL*" Then
Range(Cells(3, k), Cells(lastRow, k)).ColumnWidth = 11 'Total
End If
If checkfund Like "GENERAL*" Then
Range(Cells(3, k), Cells(lastRow, k)).ColumnWidth = 12.071432 'GF
End If
If checkfund Like "CASH*" Then
Range(Cells(3, k), Cells(lastRow, k)).ColumnWidth = 12.0714275 'CF
End If
If checkfund Like "REAPPROPRIATED*" Then
Range(Cells(3, k), Cells(lastRow, k)).ColumnWidth = 12.28422 'RF
End If
If checkfund Like "FEDERAL*" Then
Range(Cells(3, k), Cells(lastRow, k)).ColumnWidth = 12.071425 'FF
End If
If checkfund Like "*FTE" Then
Range(Cells(3, k), Cells(lastRow, k)).ColumnWidth = 7.425 'FTE
End If
Next k
'Justify 1st column Left and Bottom
Range(Cells(4, 1), Cells(lastRow, 1)).Select
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlCenter 'Bottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.ReadingOrder = xlLTR
.MergeCells = False
End With
'Justify right columns Rigth and Bottom
Range(Cells(4, 2), Cells(lastRow, lastCol)).Select
With Selection
.HorizontalAlignment = xlRight
.VerticalAlignment = xlCenter 'Bottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.ReadingOrder = xlLTR
.MergeCells = False
End With
'Padding
For j = 4 To lastRow
'MsgBox "Cell Len =" & Len(Cells(j, 1).Value)
If Len(Cells(j, 1).Value) > 41 And Len(Cells(j, 1).Value) <= 72 Then
Range(Cells(j, 1), Cells(j, 1)).Select
Range(Cells(j, 1), Cells(j, 1)).RowHeight = 20 '25
With Selection
.WrapText = True
End With
Range(Cells(j, 2), Cells(j, lastCol)).Select
With Selection
.HorizontalAlignment = xlRight
.VerticalAlignment = xlTop
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlLTR
.MergeCells = False
End With
ElseIf Len(Cells(j, 1).Value) > 72 And Len(Cells(j, 1).Value) <= 108 Then
Range(Cells(j, 1), Cells(j, 1)).Select
Range(Cells(j, 1), Cells(j, 1)).RowHeight = 30 '36
With Selection
.WrapText = True
End With
Range(Cells(j, 2), Cells(j, lastCol)).Select
With Selection
.HorizontalAlignment = xlRight
.VerticalAlignment = xlTop
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlLTR
.MergeCells = False
End With
ElseIf Len(Cells(j, 1).Value) >= 109 Then
Range(Cells(j, 1), Cells(j, 1)).Select
Range(Cells(j, 1), Cells(j, 1)).RowHeight = 40 '47
With Selection
.WrapText = True
End With
Range(Cells(j, 2), Cells(j, lastCol)).Select
With Selection
.HorizontalAlignment = xlRight
.VerticalAlignment = xlTop
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlLTR
.MergeCells = False
End With
End If
Next j
'Merging BREAKDOWN row
lastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
For i = 3 To lastRow
checktotal = Cells(i, 1).Value
If checktotal Like "BREAKDOWN*" Then
Range(Cells(i, 1), Cells(i, lastCol)).Select
With Selection
.VerticalAlignment = xlCenter
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlLTR
.MergeCells = True
.HorizontalAlignment = xlLeft
.Rows.RowHeight = 15
End With
Selection.Merge
Cells(i, 1).RowHeight = 10
End If
Next i
Cells(lastRow + 2, 1).Select
'Clear the Clipboard
Application.CutCopyMode = False
End Sub
I found the solution. It turns out it was the DPI setting after all. The user of the machine on which we were testing had changed the DPI settings in between the time we had checked the settings and actually tested.
When The DPI settings are changed, Display Settings> Advanced Display Settings> Advanced sizing of text and other items> Set a custom scaling level, the initial widths of excel columns in an excel spreadsheet change. I am not sure if this is a result of upgrading to windows 10, or the upgrade to office '16 (or both). Either way, we just have to make sure this setting is uniform on all machines.
I had a similar issue with column widths being different on different computers, and it turned out that the computer where it looked "wrong" did not have a font installed (Meiryo UI), whereas the computer where I had worked on the file did have this font. Also, the image widths were affected -- any picture I had added from the "right" computer looked too narrow on the other one.
Data after closig and opening of excelI am having a tricky situation with my excel. I have written a VBA code which collects HEX data from many CSV file and converts it into decimal and stores it into decimal. This works perfectly when tested I had no problem, I had also saved it. But when I reopen the excel half the cells are back to Hex format and only half are in decimal. I don't know why this happens. When doing it for first time it works but on saving closing it and again opening it gives me this problem
Here is the vba code
OriginalData
Sub Sample()
Dim myfiles
Dim i As Integer
Dim J As Long
Dim l As Long
Dim LastRow As Long
myfiles = Application.GetOpenFilename(filefilter:="CSV Files (*.csv), *.csv", MultiSelect:=True)
If Not IsEmpty(myfiles) Then
For i = LBound(myfiles) To UBound(myfiles)
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & myfiles(i), Destination:=Range("A" & Rows.Count).End(xlUp).Offset(1, 0))
.Name = "Sample"
.FieldNames = False
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 3
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Next i
LR = Range("A" & Rows.Count).End(xlUp).Row
For J = 2 To LR
Cells(J, 4).Value = CLng("&H" & Mid(Cells(J, 4).Value, 4, Len(Cells(J, 4).Value)))
Cells(J, 5).Value = CLng("&H" & Mid(Cells(J, 5).Value, 8, Len(Cells(J, 5).Value)))
Cells(J, 6).Value = CLng("&H" & Mid(Cells(J, 6).Value, 8, Len(Cells(J, 6).Value)))
Cells(J, 7).Value = CLng("&H" & Mid(Cells(J, 7).Value, 8, Len(Cells(J, 7).Value)))
Cells(J, 8).Value = CLng("&H" & Mid(Cells(J, 8).Value, 4, Len(Cells(J, 8).Value)))
Cells(J, 9).Value = CLng("&H" & Mid(Cells(J, 9).Value, 8, Len(Cells(J, 9).Value)))
Next
LastRow = Range("C" & Rows.Count).End(xlUp).Row
For l = 2 To LastRow
'Cells(l, 14).Value = Left(Cells(l, 3).Value, 3)
'Cells(l, 13).Value = Right(Range(l, 3).Value, 4)
'(l, 12).Value = Val(Left(Right(Cells(l, 3).Value, 7), 2))
Cells(l, 10).Value = Left(Cells(l, 3).Value, 3) + Val(Left(Right(Cells(l, 3).Value, 7), 2)) / 60 + Right(Cells(l, 3).Value, 4) / 3600
Next
Else
MsgBox "No File Selected"
End If
End Sub
I parse more than one CSV files at the same time so when on reopening only the parse of the first file remains in decimal format others change to original hex format
Edit 2: THIS HAS BEEN RESOLVED. I made the mistake of declaring a variable with the name 'Year'...
I am trying to get a cell to contain a copyright in a series of reports I deliver, and since the copyright changes with the year, I want to call the Year function to give me the current year so I don't have to update the macro every January. My code in question looks like this:
With .Cells(5, 1)
.Value = Chr(169) & " " & Year(Date) & " NCH Marketing Services, Inc"
.Font.Bold = False
.Font.Name = "Arial"
.Font.Size = 11
End With
When I execute this code, I get the error message "Compile Error: Expected Array". The odd thing is, I have tried to run this macro on three separate occasions, and it did not compile the first or third times, but the second time, it ran just fine. I have not made any edits to the code, and I have looked online for syntax/usage of the Year function, and I cannot figure out why this is working sometimes. Is there a way I can implement this in a more reliable fashion?
Edit: Below is the full code
Option Explicit
Sub RGA_Format_Reports()
Application.ScreenUpdating = False
Dim Year As Integer
Dim Quarter As Integer
Dim FolderPath As String
Dim FileName As String
Dim WorkBk As Workbook
Dim iRows As Integer
Dim iCols As Integer
Dim shpTitle As Shape
Dim shpLogo As Shape
'Quarter = InputBox("Please enter the quarter number for which the reports are being run.")
'Year = InputBox("Please enter the year for which the reports are being run.")
'FolderPath = "G:\Analytical Services\Internal Client Requests\NRS\Scheduled\" & Year & "\Quarterly RGA Store Alert Reports\" & Year & " Q" & Quarter & "\"
'FolderPath = "G:\Analytical Services\General Team Folders\Kyle\Macro Tests\RGA Reports\"
'FileName = Dir(FolderPath & "*.xl*")
'DoWhile FileName <> ""
'Set WorkBk = Workbooks.Open(FolderPath & FileName)
'With WorkBk
With ActiveWorkbook
With .ActiveSheet
iRows = .UsedRange.Rows.Count
iCols = .UsedRange.Columns.Count
.Rows.AutoFit
.Columns.AutoFit
.Columns(1).ColumnWidth = 30
ActiveWindow.FreezePanes = False
.Range("A9").Select
ActiveWindow.FreezePanes = True
With .Range(.Cells(iRows - 2, 1), .Cells(iRows, 1))
.WrapText = False
.Font.Name = "Arial"
.Font.Size = 10
End With
With .PageSetup
.TopMargin = Application.InchesToPoints(0.25)
.BottomMargin = Application.InchesToPoints(0.25)
.LeftMargin = Application.InchesToPoints(0.25)
.RightMargin = Application.InchesToPoints(0.25)
.CenterHorizontally = True
.Zoom = False
.Orientation = xlLandscape
.FitToPagesWide = 1
.FitToPagesTall = False
.PrintTitleRows = "$1:$8"
End With
.Range(.Cells(9, 3), .Cells(iRows, 3)).HorizontalAlignment = xlRight
.Range(.Cells(iRows - 4, 1), .Cells(iRows - 4, iCols)).Font.Bold = True
.Range(.Cells(iRows - 4, 1), .Cells(iRows - 4, iCols)).Interior.Color = RGB(238, 236, 225)
With .Range(.Cells(7, 9), .Cells(7, 12))
.Merge
.HorizontalAlignment = xlCenter
.Font.Bold = True
.Font.Name = "Arial"
.Font.Size = 10
.Interior.Color = RGB(238, 236, 225)
With .Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThick
End With
With .Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlThick
End With
With .Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlThick
End With
With .Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlThick
End With
.Value = "Total Billed"
End With
With .Range(.Cells(7, 13), .Cells(7, 19))
.Merge
.HorizontalAlignment = xlCenter
.Font.Bold = True
.Font.Name = "Arial"
.Font.Size = 10
.Interior.Color = RGB(238, 236, 225)
With .Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThick
End With
With .Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlThick
End With
With .Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlThick
End With
With .Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlThick
End With
.Value = "Total Adjustments"
End With
With .Range(.Cells(8, 1), .Cells(iRows - 4, 8))
With .Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThick
End With
With .Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlThick
End With
With .Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlThick
End With
With .Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlThick
End With
End With
With .Range(.Cells(7, 9), .Cells(iRows - 4, 12))
With .Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThick
End With
With .Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlThick
End With
With .Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlThick
End With
With .Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlThick
End With
End With
With .Range(.Cells(7, 13), .Cells(iRows - 4, 19))
With .Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThick
End With
With .Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlThick
End With
With .Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlThick
End With
With .Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlThick
End With
End With
If .Cells(9, 4) = 0 Then
Columns("D:E").Delete
End If
For iRows = 1 To 4
.Cells(iRows, 1).Font.Bold = True
.Cells(iRows, 1).Font.Name = "Arial"
If iRows = 1 Then
.Cells(iRows, 1).Font.Size = 14
Else
.Cells(iRows, 1).Font.Size = 12
End If
Next iRows
With .Cells(5, 1)
.Value = Chr(169) & " " & Year(Date) & " NCH Marketing Services, Inc"
.Font.Bold = False
.Font.Name = "Arial"
.Font.Size = 11
End With
.Columns("A").ColumnWidth = 200
.Range(Cells(1, 1), Cells(5, 1)).WrapText = False
.Range(Cells(1, 1), Cells(5, 1)).Copy
.Range("B1").Select
Application.Wait (Now + TimeValue("00:00:01"))
.Pictures.Paste.Select
.Range(Cells(1, 1), Cells(5, 1)).ClearContents
.Columns("A").AutoFit
.Range("A1").Select
Set shpTitle = .Shapes("Picture 1")
With shpTitle
.Name = "Title Picture"
.Placement = xlFreeFloating
End With
Set shpLogo = .Shapes.AddPicture("G:\Analytical Services\AS Tools\AS Templates\NCH Logo.png", False, True, 1, 1, 60, 67)
With shpLogo
.Name = "Logo Picture"
.Placement = xlFreeFloating
End With
With shpTitle
.Left = 67
End With
.Columns("A").ColumnWidth = 30
End With
End With
End Sub
#ShaiRado pointed out that I had set a variable with the name of 'Year'. I am aware that declaring variables with the same name as functions is a big no no; I just had a mental lapse. Changing the variable declaration fixed my problem. Thanks #ShaiRado.
I have this code that obviously use Select, .Activate,...and I understand it's not a good practice in addition the application is craching now and then so thats probably because of using Select...
I'm pretty new to VBA and would appreciate help on how to change this code to NOT use Select.Activate, ActiveSheet,ActiveCell and maybe other consideration in order to get it more efficient.
Sub FormatText()
Sheets("A4").Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) - 2, BoxColOffset(Box)).Activate
With ActiveCell.Font
.Name = "Calibri"
.Size = 11
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
.Bold = False
End With
With Range(Cells(PageRowOffset(Page) + BoxRowOffset(Box), 1 + BoxColOffset(Box)), Cells(PageRowOffset(Page) + BoxRowOffset(Box) + 3, 1 + BoxColOffset(Box) + 1)).Font
.Name = "Calibri"
.Size = 8
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
.Bold = False
End With
With Range(Cells(PageRowOffset(Page) + BoxRowOffset(Box) + 4, 1 + BoxColOffset(Box)), Cells(PageRowOffset(Page) + BoxRowOffset(Box) + 7, 1 + BoxColOffset(Box) + 1)).Font
.Name = "Calibri"
.Size = 7
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
.Bold = False
End With
Range(Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) + 1, 1 + BoxColOffset(Box) + 1), Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) + 2, 1 + BoxColOffset(Box) + 1)).Select
Range(Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) + 1, 1 + BoxColOffset(Box) + 1), Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) + 2, 1 + BoxColOffset(Box) + 1)).NumberFormat = "#,##0.00"
With Selection
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlTop
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
End Sub
**How do you attack something like this?**
Sheets("report").Activate
If fcnHasImage(Cells(15 + i, 24)) Then
ActiveSheet.Cells(15 + i, 24).CopyPicture
Else
ActiveSheet.Cells(15 + i, 2).CopyPicture
End If
Sheets("A4").Select '< - How should I this be changed?
Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) + 7, BoxColOffset(Box) + 1).Select '< - This I guess is by changing it to Range?/Henrik
ActiveSheet.Paste
Application.CutCopyMode = False
ShowProgress 'Run macro
ActiveSheet.Cells(1, 25).Value = 15 + i +
End If...
The below is a shortened-up version of your code:
Sub FormatText()
With Sheets("A4").Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) - 2, BoxColOffset(Box)).Font
.Name = "Calibri"
.Size = 11
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.ThemeFont = xlThemeFontMinor
End With
With Range(Cells(PageRowOffset(Page) + BoxRowOffset(Box), 1 + BoxColOffset(Box)), Cells(PageRowOffset(Page) + BoxRowOffset(Box) + 3, 1 + BoxColOffset(Box) + 1)).Font
.Name = "Calibri"
.Size = 8
.Underline = xlUnderlineStyleNone
.ThemeFont = xlThemeFontMinor
End With
With Range(Cells(PageRowOffset(Page) + BoxRowOffset(Box) + 4, 1 + BoxColOffset(Box)), Cells(PageRowOffset(Page) + BoxRowOffset(Box) + 7, 1 + BoxColOffset(Box) + 1)).Font
.Name = "Calibri"
.Size = 7
.Underline = xlUnderlineStyleNone
.ThemeFont = xlThemeFontMinor
End With
Range(Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) + 1, 1 + BoxColOffset(Box) + 1), Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) + 2, 1 + BoxColOffset(Box) + 1)).NumberFormat = "#,##0.00"
With Range(Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) + 1, 1 + BoxColOffset(Box) + 1), Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) + 2, 1 + BoxColOffset(Box) + 1))
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlTop
.ReadingOrder = xlContext
End With
End Sub
Select and Activate are basically just methods that are used in recording macros. To trim down a macro from there, you can do the following:
Anywhere ActiveCell is used, simply replace it with the Range reference that .Activate was called on. (In your case, the first With ActiveCell.Font would become With Sheets("A4").Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) - 2, BoxColOffset(Box)).Font)
Anywhere Selection is used, simply replace it with the Range reference that .Select was called on. (In your case, With Selection would become With Range(Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) + 1, 1 + BoxColOffset(Box) + 1), Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) + 2, 1 + BoxColOffset(Box) + 1)))
As an aside, when you correct that last With Selection block, you'll be able to move the .NumberFormat adjustment into the With block as well.
Some additional advice would be to get in the habit of establishing Worksheet objects that you can store the specific sheets your working in. So I would do something like Dim currentSheet As Worksheet and then somewhere before this block of code you've posted (where appropriate) Set currentSheet = Sheets("A4"). You'll have to update any Range(...) and Cells(...) calls to be currentSheet.Range(...), but the advantage of this is that your Range and Cells calls will always reference Sheets("A4") -- they won't accidentally switch context if you make modifications to this macro later on. This is how you also avoid relying on ActiveSheet, in general.
Whenever you have to scroll horizontally to read your code; consider refactoring.
If you have a Range reference that contains two Cell references that share variables it would probably be better to use Range Resize.
Both of these examples are referring to the same Range. Using Range Resize we are able to remove shared variable.
Range(Cells(a + b, c), Cells(a + b + 10, c + 10))
Cells(a + b, c).Resize(10 + 1, 10 + 1)
Note: You will have to add one to the Columns and Rows parameter.
Option Explicit
Sub FormatText()
Dim bc As Long, br As Long, pr As Long
bc = BoxColOffset(Box)
br = BoxRowOffset(Box)
pr = PageRowOffset(Page)
With Worksheets("A4")
With .Cells(1 + pr + br - 2, bc).Font
.Name = "Calibri"
.Size = 11
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
.Bold = False
End With
End With
With Worksheets("Sheet1")
With .Cells(pr + br, 1 + bc).Resize(4, 2).Font
.Name = "Calibri"
.Size = 8
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
.Bold = False
End With
With .Cells(pr + br + 4, 1 + bc).Resize(4, 2).Font
.Name = "Calibri"
.Size = 7
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
.Bold = False
End With
With .Cells(1 + pr + br + 1, 1 + bc + 1).Resize(2)
.NumberFormat = "#,##0.00"
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlTop
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
End With
'Updated to answer:'**How do you attack something like this?**
With Worksheets("report")
If fcnHasImage(.Cells(15 + i, 24)) Then
.Cells(15 + i, 24).CopyPicture
Else
.Cells(15 + i, 2).CopyPicture
End If
Sheets("A4").Cells(1 + pr + br + 7, bc + 1).PasteSpecial
ShowProgress 'Run macro
.Cells(1, 25).Value = 15 + i
End With
End Sub
From the image below, I want to write a vba where cells in the column b will be equal to group above. So for example, column b for Activity 1.1 and Activity 1.2 would be equal to Group 1, and column b for Activity 2.1 and Activity 2.2 would be equal to Group 2.
c d e f g h i
Any ideas on where to start? Currently I have a two macros: One creates a group below a selected group and the other creates a line below a selected line. I'm thinking that when creating a new line I could somehow equate column b to the closest merged cell above my new line.
How could I find the closest merged cell above a selected row?
The code to create a new line is below:
Sub newLine()
Dim currCell As Integer
Dim newCell As Integer
currCell = ActiveCell.Select
Selection.Offset(1).EntireRow.Insert
ActiveCell.Offset(1, 0).Select
Cells(Selection.Row, 3).FormulaR1C1 = "=IF(RC4=""Complete"",1,IF(RC4=""Late"",2,IF(RC4=""At Risk"",3,IF(RC4=""On Schedule"",4,5))))"
With Cells(Selection.Row, 3)
.FormatConditions.Delete
.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=1"
.FormatConditions(1).Interior.Color = RGB(0, 112, 192)
.FormatConditions(1).Font.Color = RGB(0, 112, 192)
.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=2"
.FormatConditions(2).Interior.Color = RGB(192, 0, 0)
.FormatConditions(2).Font.Color = RGB(192, 0, 0)
.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=3"
.FormatConditions(3).Interior.Color = RGB(255, 192, 0)
.FormatConditions(3).Font.Color = RGB(255, 192, 0)
.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=4"
.FormatConditions(4).Interior.Color = RGB(146, 208, 80)
.FormatConditions(4).Font.Color = RGB(146, 208, 80)
.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=5"
.FormatConditions(5).Interior.Color = RGB(255, 255, 255)
.FormatConditions(5).Font.Color = RGB(255, 255, 255)
End With
Cells(Selection.Row, 4).Select
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="Complete, Late, At Risk, On Schedule"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = "Select Status"
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Cells(Selection.Row, 4) = "[Enter Status]"
Cells(Selection.Row, 4).HorizontalAlignment = xlLeft
Cells(Selection.Row, 5) = "[Enter Activity]"
Cells(Selection.Row, 5).HorizontalAlignment = xlLeft
Cells(Selection.Row, 6) = "[Enter Task]"
Cells(Selection.Row, 6).HorizontalAlignment = xlLeft
Cells(Selection.Row, 7) = "[Enter Responsability]"
Cells(Selection.Row, 7).HorizontalAlignment = xlLeft
Cells(Selection.Row, 8) = "[Enter Start Date]"
Cells(Selection.Row, 8).HorizontalAlignment = xlRight
Cells(Selection.Row, 9) = "[Enter Comp Date]"
Cells(Selection.Row, 9).HorizontalAlignment = xlRight
Range(Cells(Selection.Row, 4), Cells(Selection.Row, 9)).Font.Bold = False
Range(Cells(Selection.Row, 4), Cells(Selection.Row, 9)).Font.Size = 8
Range(Cells(Selection.Row, 4), Cells(Selection.Row, 9)).RowHeight = 11.25
Range(Cells(Selection.Row, 4), Cells(Selection.Row, 7)).HorizontalAlignment = xlLeft
Range(Cells(Selection.Row, 4), Cells(Selection.Row, 7)).NumberFormat = "General"
Range(Cells(Selection.Row, 8), Cells(Selection.Row, 9)).HorizontalAlignment = xlRight
Range(Cells(Selection.Row, 8), Cells(Selection.Row, 9)).NumberFormat = "m/d/yyyy"
End Sub
Any ideas?
Thank you!
MergeCells can help you out here.
Sub WhichLineIsMerged()
Dim row As Long
For row = ActiveCell.row To 1 Step -1
If Cells(row, 1).MergeCells Then
MsgBox "There are merged cells in row " & row
End If
Next row
End Sub
This sub only checks one cell on each line. As written, it checks Column A. You can adjust as needed.
In case anyone was interested, here's how I solved this:
Sub testGroupNum()
Dim i As Long
Dim LastRow As Integer
Dim startRow As Integer
LastRow = Cells(Rows.Count, "H").End(xlUp).Row
startRow = Selection.Row
For i = startRow To 11 Step -1
If Cells(i, 4).MergeCells = True Then
Cells(startRow, 2) = Cells(i, 4)
Exit For
End If
Next
End Sub