Range Class Selection Syntax Error Between Multiple Sheets - vba

I have been designing a macro that imports text files into Excel. The program was designed to initially import all data into sheet 1, but after getting feedback I was told to have it bring all data into sheet 2 instead. This macro had no trouble working when using commands such as Activesheet at the beginning of code lines, because sheet1 was always the active sheet. *Note both all sheets have their default names.
I have gone in and tried to change all my range fns to regard sheet 2 instead by typing Worksheets("Sheet2").Range("A1")... ,but this has given me the
"Select method of Range class"
error. This error occurs after my initial fn to import the file using a Query table.
Option Explicit
Sub importtxt()
Dim txtloc As Variant
Dim build As String
Dim bit As String
Dim rng As Range
'Asks user for the build number that has been imported, then assigns that
string to cell B1
build = InputBox("What build of SoundCheck is this?")
'Prompt Bitness
bit = InputBox("Please provide the bitness of this SoundCheck")
'Asks user for location of the Time_Memlog.txt file to be imported
txtloc = Application.GetOpenFilename _
(FileFilter:="Text Filer (*.txt),*.txt", _
title:="Open File(s)", MultiSelect:=False)
'Imports .txt file designated in the txtloc string
With Sheets("Sheet2").QueryTables.Add(Connection:="TEXT;" & txtloc,
destination:=Worksheets(2).Range("$A$1"))
.Name = "Sample"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
'Clears the garbage in cell A1
Worksheets("Sheet2").Range("$A$1").Select
ActiveCell.Clear
'Places the string build in cell A1
Worksheets(2).Range("A1").Select
ActiveCell.Value = "Build:"
Worksheets(2).Range("B1").Select
ActiveCell.Value = build
Worksheets(2).Range("C1").Select
ActiveCell.Value = bit
'Selects all columns of the Time_Memlog and adjusts the column width to fit
heading
Worksheets(2).Range("A1:S10003").Select
Selection.Columns.AutoFit
'Makes column headers bold text
Sheets("Sheet2").Range("A2:D2").Font.Bold = True
'Create borders around cell range A2:D2
Set rng = Worksheets(2).Range("A2:D2")
With rng.Borders
.LineStyle = xlContinuous
.Weight = xlThin
End With
'Give background color to cells A2:D2
With rng.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent6
.TintAndShade = 0.599993896298105
.PatternTintAndShade = 0
End With
'Aligns all cells below Column headers to the left
Worksheets(2).Range("A3:D10003").Select
Selection.HorizontalAlignment = xlLeft
'Give background color to cells A1:C1
Worksheets(2).Range("A1:C1").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = -0.149998474074526
.PatternTintAndShade = 0
End With
Selection.HorizontalAlignment = xlLeft
Worksheets(2).Range("D1").Select
Selection.Clear
End Sub
This seems like a very simple problem, yet I don't know how to get around these errors.

Two answers:
The bad news: You cannot select a cell or range from a worksheet that is not active.
The good news: No need to select a cell to assign a value (or do anything else with it). In fact you should avoid to select anything within VBA, there is nearly no reason to do so. Instead, simply do something like
with Worksheets(2)
.range("A2").value = "Build:"
' or: .cells(1,1).value = "Build:"
...
end with

Related

Excel VBA - Loop search for value then color row

This macro is supposed to find the value NULL in column "W" and paint the row it found NULL on in a color. It does that fine however if I try to search for a number in the same column(that i know exists there) it doesn't seem to find the value. Any help would be appreciated.
Sub e()
MsgBox "some question?", , "Marvin The Paranoid Android"
Dim fNameAndPath As Variant, wb As Workbook
Dim LastRow As Long, i As Long, sht As Worksheet
Dim myValue As Variant
fNameAndPath = Application.GetOpenFilename(FileFilter:="Excel Files (*.XLSX), *.XLSX", Title:="Èçáåðåòå ôàéë ñ èìå /Ðåâîëâèíãè/")
If fNameAndPath = False Then Exit Sub
Set wb = Workbooks.Open(fNameAndPath)
Set sht = wb.Worksheets("Sheet1")
X = wb.Name
Windows(X).Activate
'Macro optimization
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
'000000000
ActiveWindow.Zoom = 85
Rows("1:1").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Range("A1:W1").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Range("A:E,L:N").EntireColumn.AutoFit
Columns("F:F").ColumnWidth = 6.14
Columns("G:G").ColumnWidth = 6.43
Columns("H:K").ColumnWidth = 5.43
Range("O:R,T:V").ColumnWidth = 4.71
Columns("S:S").ColumnWidth = 14.71
Rows("1:1").RowHeight = 54.54
Range("A1").Select
myValue = InputBox("Give me some input")
LastRow = sht.Cells(sht.Rows.Count, "W").End(xlUp).row
For r = 1 To LastRow
If Cells(r, Columns("W").Column).Value = myValue Then
Rows(r).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Next r
Range("A1").Select
Application.Calculation = xlCalculationAutomatic
wb.Close SaveChanges:=True 'or false
'Reverse macro optimization
Application.EnableEvents = True
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "Îáðàáîòèõ ôàéë /Ðåâîëâèíãè/...", , "Marvin The Paranoid Android"
End Sub
Autofilter() method of Range object can detect "23" both as number and a text:
With sht
With .Range("W1", .Cells(.Rows.Count, "W").End(xlUp)) '<--| consider column "W" values down to its last non empty row
.AutoFilter field:=1, Criteria1:=myValue '<--| filter column "W" on 'myValue'
If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then '<--| if any values match...
With .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Interior '<--|... consider only filtered values, and apply formatting
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
End With
.ShowAllData '<--| show all rows back...
End With
Try replacing your For loop with the piece of code below.
If you are using Decimal values, or values larger than Integer, make the changes from CInt to your needs:
For r = 1 To LastRow
If sht.Cells(r, "W").Value = CInt(myValue) Then
sht.Rows(r).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Next r
Try replacing your loop with this:
Dim tempFind
Set tempFind = ActiveSheet.Columns("W").Find(What:=myValue, LookIn:=xlValues, LookAt:=xlWhole, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
If Not tempFind Is Nothing Then
With Range(tempFind.Address).Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Else
MsgBox "Not Found!"
End If
When you say:-
if I try to search for a number in the same column(that i know exists there) it doesn't seem to find the value
I assuming you are referring to the below line from your code not returning true and running the code within the If statement.
If Cells(r, Columns("W").Column).Value = myValue Then
In short, if its not finding a match then there is not a match, but it can be hard to see sometimes.
Examples of not matching when you think it should are:-
If the cell contains 12.12121212 but is formatted to show it as 12.12, if you search for 12.12 (as you think that would match) it will not match.
If the cell contains leading or trailing spaces, '12.12 ' (space at the end), if you search for 12.12 (no space at the end) it will not match.
We can see what you are trying to match or what you think should be a match from your question but the above should be the information needed to work the answer out from your content.
Based on the comments, try altering your code with the below, I've added some debugging lines to help understand why its failing: -
'If the value is null it will skip trying to check it, this mean no type mismatch error
If Not IsNull(Cells(r, Columns("W").Column).Value) then
'This prints the value in the cell, the searched value, and if its seen as a match
Debug.Print "'" & Cells(r, Columns("W").Column).Value & "' ,'" & myValue & "', " & (Cells(r, Columns("W").Column).Value = myValue)
'Compares them both as Long data types
If CLng(Cells(r, Columns("W").Column).Value) = CLng(myValue) Then
'Your code
End If
End If

Excel VBA Range Variable Throws Error 1004 - I'm in

I need your help please. I am new to using ranges as variables, so there maybe something obvious I'm missing but I can't seem to find a solution after a lot of googling.
I am formatting four sheets of data (headings, pretty fill colour, nice borders). They are all pretty much the same, but they have a varying number of columns. To save repetitious code I've written one procedure to do the formatting and another to change the variables and call the formatting code.
sample of the calling code:
' Set Customer detail variables.
varGlobalID = Sheets(varWST1Dockets).Cells(2, 13).Value
varCustomerName = Sheets(varWST1Dockets).Cells(2, 14).Value
' Format Suspended
' Set Variables
varReportHeading = "Suspended Dockets Investigation"
Set rngDataHeadings = Range("B11", "T11")
Range("B1048576").End(xlUp).Select
Set rngDataTable = Range(Selection, "T11")
Range("B1048576").End(xlUp).Select
Set rngData = Range(Selection, "T12")
' Run Format Reports Procedure
Sheets(varWSSuspended).Select
Call FormatReports
sample of formatting code
' Format Data Headings
rngDataHeadings.Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = -4300032
.PatternTintAndShade = 0
End With
With Selection.Font
.ColorIndex = 2
.TintAndShade = 0
.Bold = True
End With
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlCenter
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
' Apply Borders
rngDataTable.Select
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 2
.TintAndShade = 0
.Weight = xlMedium
End With
The code seems to work on the first run of the variables but not the second. Do I need to unload them before resetting? Or am I doing something else stupidly obviously wrong?
Thanks in advance.
Set rngDataHeadings = Range("B11", "T11") references B11:T11 of the ActiveSheet. Selecting another worksheet and try rngDataHeadings.Select will throw an exception Runtime Error '1004' Select method of Range class failed
It's best to avoid Select and Active. You should watch Selecting Cells (Range, Cells, Activecell, End, Offset)
If you have standard tables this will work.
Sub FormatTable(wsWorksheet As Worksheet, HeaderAddress As String)
Dim rDataBody As Range
Dim rHeader As Range
With wsWorksheet
Set rHeader = .Range(HeaderAddress, .Range(HeaderAddress).End(xlToRight))
Set rDataBody = Range(HeaderAddress).CurrentRegion
Set rDataBody = rDataBody.Offset(1).Resize(rDataBody.Rows.Count - 1)
End With
With rHeader.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = -4300032
.PatternTintAndShade = 0
End With
With rHeader.Font
.ColorIndex = 2
.TintAndShade = 0
.Bold = True
End With
With rHeader
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlCenter
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
' Apply Borders
With rDataBody.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 2
.TintAndShade = 0
.Weight = xlMedium
End With
End Sub
Call it like this
FormatTable Worksheets("Sheet1"), "B11"

Excel VBA Columns in chart - format font, color, alignment etc

I am having troubles formatting columns in a chart to match a specific font, colour, alignment etc.
This code, while focused on column A:A, it applies to every single cell in the worksheet. I only want it to affect Column A:
Sub PGMNumber()
'
' PGMNumber Macro
'
'
Range("A:A").Select
With Selection.Font
.Name = "Arial"
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.Color = -16776961
.TintAndShade = 0
.ThemeFont = xlThemeFontNone
End With
With Selection.Font
.Name = "Arial"
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.Color = -16776961
.TintAndShade = 0
.ThemeFont = xlThemeFontNone
End With
Selection.Font.Bold = False
Selection.Font.Bold = True
With Selection.Font
.Color = -10477568
.TintAndShade = 0
End With
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Columns("A:A").ColumnWidth = 9.43
End Sub
This was done by recording my steps. All I need is FontName, Colour, Bold, Size and Alignment. Deleting what I don't need breaks the code :(
Can someone help me simplify the code so it will only affect column A?
Also, how do I add the option to include other columns, for example B, C, D, etc.
Lastly, can I have the macro start formatting from A6 downward, B6 downward, C6 downward, etc? That way the header of the chart remains untouched.
Thank you!
This will format column A from row 6 down. There were two font colors in there, I removed the first one. To change the column of this code, change the "A"s in the Range() to the column you want to target, e.g. .Range("B6:B" & .Cells(.Rows.Count, "B") etc.
Sub PGMNumber()
' PGMNumber Macro
Dim FormatRange As Range
With ThisWorkbook.ActiveSheet
Set FormatRange = .Range("A6:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
End With
With FormatRange
With .Font
.Name = "Arial"
.Size = 10
.Bold = True
.Color = -10477568
End With
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
End With
End Sub
You can use this macro where the two cells in Range() are your top left cell and bottom right cell of the range to format.
Sub PGMNumber()
With Range(Cells(6, "A"), Cells(Rows.Count, "D"))
With .Font
.Name = "Arial"
.Size = 10
.Color = -16776961
.Bold = True
End With
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
End With
End Sub

Copy data from one sheet and paste into the first blank cell in column A of another sheet

Sub ImportFixed()
'
Sheets("Front-Page").Select
Sheets("SPROC").Visible = True
Sheets("SPROC").Select
ThisWorkbook.RefreshALL
DoEvents
'Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False
Sheets("SPROC").Select
Range("J2").Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Master-Data-Sheet").Select
Range("A1914").Select
ActiveSheet.Paste
Sheets("SPROC").Select
Range("N2").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Master-Data-Sheet").Columns("N:N").Range("N1914").Paste
Cells.Select
Application.CutCopyMode = False
With Selection.Font
.Size = 9
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.TintAndShade = 0
End With
With Selection.Font
.Name = "Calibri"
.Size = 9
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With
Columns("A:H").Select
With Selection
.HorizontalAlignment = xlGeneral
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
With Selection
.HorizontalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Columns("M:N").Select
With Selection
.HorizontalAlignment = xlGeneral
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
With Selection
.HorizontalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Range("L16108").Select
Range("J2105").Select
Range(Selection, Selection.End(xlDown)).Select
Range("J2137").Select
Range("N2137").Select
Sheets("SPROC").Select
ActiveWindow.SelectedSheets.Visible = False
ActiveWindow.ScrollWorkbookTabs Sheets:=-2
Sheets("Master-Data-Sheet").Select
End Sub
I have a report that has a sheet named SPROC. This sheet is refreshed each Monday and pulls through data for that day from a SQL query (any other data on that sheet is overwritten) . What I then want to do is select ALL the data (Columns A:N - The number of rows changes each week so the range isn't fixed) and paste it into the first blank cell in column A on a sheet named Master-Data-Sheet. This second sheet contains ALL the data for previous weeks and is used to populate ALL my pivot tables and graphs etc on various other worksheets. At present I have recorded a Macro but instead of finding the last blank row, it is using a specific range which means that when I run the macro, it overwrites data in the Master Data file. Any Suggestions?
I have included a copy of the VBA code (it also does a lot of other functions so apologies if it is a little long). I think it is lines 20 and 359 where the issue is occurring but I have no idea what to do to fix it (I have tried ALL manner of different variations).
Pretty classical matter, must have a lot of similar question and please get rid of scrolls and things like this in record macros...
try this :
Sub Macro2()
'
Dim ShIn As Worksheet
Dim ShOut As Worksheet
Set ShIn = ThisWorkbook.Sheets("SPROC")
Set ShOut = ThisWorkbook.Sheets("Master-Data-Sheet")
'ShIn.Cells(2, 1).End(xlToRight).Column
Dim RgTotalInput As String
Dim RgTotalOutput As String
RgTotalInput = "$A$2:$" & ColLet(ShIn.Cells(1, 1).End(xlToRight).Column) & "$" & ShIn.Cells(Rows.Count, 1).End(xlUp).Row
RgTotalOutput = "$A$" & ShOut.Cells(Rows.Count, 1).End(xlUp).Row + 1
ShIn.Range(RgTotalInput).Copy Destination:=ShOut.Range(RgTotalOutput)
End Sub
Public Function ColLet(ByVal ColNb As Integer) As String
Dim ColLetTemp As String
Select Case ColNb
Case Is < 27
ColLetTemp = Chr(64 + ColNb)
Case Is > 26
If Int(ColNb / 26) <> ColNb / 26 Then
ColLetTemp = Chr(64 + Int(ColNb / 26)) & Chr(64 + ColNb - 26 * Int(ColNb / 26))
Else
ColLetTemp = Chr(64 + Int(ColNb / 26) - 1) & Chr(64 + 26)
End If
Case Else
End Select
ColLet = ColLetTemp
End Function

Error 1004 while creating Pivot Table on Dynamic data using VBA

I am experiencing the following issue while creating Pivot table using VBA. The source data is dynamic. While creating Pivot table I receive following error sometimes and it works fine.
Run-time error '1004':
The PivotTable field name is not valid. To create a PivotTable report, you must use data that is organized as a list with labeled columns. If you are changing the name of a PivotTable field, you must type a new name for the field.
'pivot table
'Adding new worksheet
Set ws = wbReport.Worksheets.add
'Set rangept = Sheets("Non_Complaince_CHOC_CA").UsedRange.Select
'ls = wbReport.Sheets(ReportSheet).Cells(Rows.Count, 1).End(xlUp).Row
ls = wbReport.Sheets(ReportSheet).Range("A" & Rows.Count).End(xlUp).Row
'Creating Pivot cache
Set pc = wbReport.PivotCaches.Create(xlDatabase, "" & ReportSheet & "!r1c1:r" & ls & "c12")
'Set pc = ActiveWorkbook.PivotCaches.Create(xlDatabase, "rangept")
'Creating Pivot table
Set pt = pc.CreatePivotTable(ws.Range("B3"))
'Setting Fields
With pt.PivotFields("Downtime Requirement")
.Orientation = xlRowField
.Position = 1
End With
'set value field
With pt.PivotFields("Downtime Requirement")
.Orientation = xlDataField
.Function = xlCount
.Position = 1
End With
ws.Name = "Failing_PI_Summary"
ws.Range("B2:C2").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Selection.Merge
ActiveCell.FormulaR1C1 = "Prod Domain Failing PI Summary for " & Client
ws.Range("B2:C2").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.PatternTintAndShade = 0
End With
With Selection.Font
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
End With
Selection.Font.Bold = True
ws.Range("A1").Select
Application.CutCopyMode = False
wbReport.Save
'end pivot table