How to create Excel Table by VBA at runtime? - vba

During execution of macro I reads multiple excel file and creates a new excel file, i build a similar sheet:
At runtime by VBA I want to set this area and create a table, add Total Row and get the following result:
Thank you :-)

Like this:
Range("A1:I9").Select
ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$I$9"), , xlYes).Name = "Table1"
ActiveSheet.ListObjects("Table1").ShowTotals = True
ActiveSheet.ListObjects("Table1").ListColumns("B").TotalsCalculation = xlTotalsCalculationSum
ActiveSheet.ListObjects("Table1").ListColumns("C").TotalsCalculation = xlTotalsCalculationSum
'Repeat row above until column I
I got this by recording a VBA Macro. If you are not familiar with Macro recording see link here.

Related

Excel VBA, Entering Formula in Table Only Specific Row, Not Entire Column

I'm using VBA in Excel to enter a formula in a specific cell within a table, but don't want the entire column to get this formula.
When doing it manually, Excel gives me the option to 'Undo Calculated Column', but not when it's done through code.
My code is as follows:
Dim url As String
url="https://example.com/myurl"
ThisWorkbook.Worksheets("PO Info").Range("E3").FormulaR1C1 = "=Hyperlink(""" & url & """,""Supplier Portal"")"
Any help would be greatly appreciated.
Try:
Application.AutoCorrect.AutoFillFormulasInLists = False

Inserting a row into a Word Table with Excel VBA

I have written a program to migrate a set of data from Excel into Word. The problem is that the format of form in word the must be entered into a new file in a very specific format, with new lines being inserted into the line data. In other words, I have information that is currently held in column two for every row in excel, that now has to be moved into a single row in the sheet I am solving this through adding a row after the table is created in word and then merging them, but the code I found keeps producing the runtime error 4120 Bad parameter. I am guessing that the code that I am using is actually for use within word not from excel. Any help on the proper code would be appreciated.
If section1 = True Then
'wdDoc.Tables(1).Rows.Add BeforeRow:=.Rows(2)
wdDoc.Tables.Rows.Add (2)
With wdDoc.Tables(1)
.Cell(Row:=2, Column:=2).Merge _
MergeTo:=.Cell(Row:=2, Column:=10)
.Borders.Enable = False
wdDoc.Tables(1).Cell(2, 2).Range.Text = "Section I - Authorized Ship Changes"
End With
Else
End If
In this line of code:
wdDoc.Tables.Rows.Add (2)
the argument for the Add method must be a Row object. So something like:
wdDoc.Tables.Rows.Add wdDoc.Tables.Rows(2)
will add a new row before row 2.
Hope that helps.

Excel Macro to Copy Data From a Worksheet Yields the Query Definition instead of Data

As the title says, I'm trying to copy data from a particular file into a new tab in my workbook, but the macro only copies the query definition that (I assume) was used to retrieve the data itself.
I've already removed any connections to external sources, but that didn't fix the problem. Here's a screenshot of the paste results:
Here's the portion of my code I am using to paste:
Set DestWS = wkbDest.Sheets(Curr_Input_File)
If Len(wkbDest.Sheets(Curr_Input_File).Range("A1").Value) > 0 Then
wkbDest.Sheets(Curr_Input_File).UsedRange.ClearContents
SheetToCopy.UsedRange.Copy
DestWS.Range("A1").PasteSpecial xlPasteAll
Application.CutCopyMode = False
Else
SheetToCopy.UsedRange.Copy
DestWS.Range("A1").PasteSpecial xlPasteAll
Application.CutCopyMode = False
End If
I know the copy/paste loop works since all the other files are copied/pasted without issue. However, for this file only, I'm having the issue as described above. How can I code it to paste the actual data instead of the query? FWIW, I can't see the query anywhere in the source data file.
Okay, the answer is obvious but I figured it out. There was a hidden sheet with the SQL query definition. My copy code was just copying the first tab in the workbook by default SheetToCopy = wkbSource.Sheets(1), thus it was grabbing the SQL query.
I didn't even know you could hide sheets. It's done by going to the Home tab, under the 'Cells' section click Format-->Hide & Unhide-->Unhide Sheet.

Create a table using existing data via VBA, using the CURRENTREGION function

So I'm 90% of the way into creating my first big macro project. Thanks for all your help so far everyone! I've come up against an issue however - which I think should be the last issue I should face before putting the macro into use.
I've written a macro which copies the data presented in a master spreadsheet, creates a new workbook in the target location, then creates a table using the information provided.
What I want to do is use CurrentRegion to allow the data to alter month-to-month. I think the code should go something like this
`GeneratePivotTables Macro
'Converts information stored on sheet "Data" to a table
Dim TABLE As Range
Set TABLE = Sheets("Data").A1.CurrentRegion
Sheets("Data").Listobjects.Add(x1SrcRange, Range("TABLE"), ,1Xyes).Name="Data"
I know this as presented is incorrect, but I'd like some help just parsing this correctly! My aim is to then be able to use the table "Data" to create pivot tables.
The following code converts the CurrentRegion around cell A1 into a table. See if you can modify it for your needs.
Sub ConvertRangetoTable()
Dim rngTable As Range
Set rngTable = Sheets("Data").Range("A1").CurrentRegion
Sheets("Data").ListObjects.Add(xlSrcRange, rngTable, , xlYes).Name = "All_Data"
End Sub
This seems to be sufficient
Sub M_snb()
Sheet1.ListObjects.Add(1, [A1].CurrentRegion, , 1).Name = "snb_001"
End Sub

Copy data from multiple excel sheets and append that to a single excel sheet using VBScript

The scenario is as follows:
I have an excel (.xls) file with data. (eg. A.xls)
The Data on this excel file are on a single worksheet (Sheet 1).
The number of columns in this file is fixed i.e. 8
However, the number of rows containing data may vary from time to time. (This file is updated by another program from time to time)
Now, I have another excel file (eg. B.xls) with similar type of data but not same as the contents of A.xls.
The number of columns in B.xls is 8 as well. However, the number of rows containing data are unknown.
I want to copy the contents of A.xls, 2nd row onwards (excluding the 1st row containing the column headers) and append/paste the same to the B.xls file, without over-writing the existing data on B.xls.
With all these details in mind, I want to write a vbscript to automate this task.
Please help.
Thanks a lot, in advance.
It needs a lot of cleanup, but something like this should work. I'll clean it up a bit and then make an edit.
Sub CopyRows()
' Choose the name of the Second Workbook and last column.
' It must be in the same directory as your First Workbook.
secondWorkbook = "B.xls"
lastColumn = "H"
' A couple more variables
currentWorkbook = ThisWorkbook.Name
Workbooks.Open ThisWorkbook.Path & "\" & secondWorkbook
' In the First Workbook, find and select the first empty
' cell in column A on the first Worksheet.
Windows(currentWorkbook).Activate
With Worksheets(1).Columns("A:A")
Set c = .Find("", LookIn:=xlValues)
If Not c Is Nothing Then
' Select and copy from A2 to the end.
secondAddress = Replace(c.Address, "$A$", "")
Range("A2:" & lastColumn & CStr(CInt(secondAddress) - 1)).Select
Selection.Copy
End If
End With
' Activate the Second Workbook
Windows(secondWorkbook).Activate
With Worksheets(1).Columns("A:A")
Set c = .Find("", LookIn:=xlValues)
If Not c Is Nothing Then
' Select and paste the data from First Workbook
Range(c.Address).Select
ActiveSheet.Paste
End If
End With
End Sub
Update: That should do the trick. I copied from the wrong workbook the first time around, too. Let me know if you have questions.
This is something the Macro Recoder could have written for you. You would come out with different approach.
Turn on recording. Open A.xls and B.xls. Move down one row on a. Press Shift+End then →, then Shift+End+↓. Then Ctrl+C to copy your data. Switch back to B. End+↓, ↓. Ctrl+V to paste. Turn off recording.
You can record in Excel.
Alt+T,M,R
then Home key then ↑. Stop recording.
Look what Excel wrote
Selection.End(xlUp).Select
or if you had of recorded Go To dialog
Application.Goto Reference:="R1C1"
or if you had of recorded Ctrl+Home
Range("A1").Select
To convert to vbscript
Record the steps in excel macro recorder. You have to rewrite it a bit because it uses a type of syntax that vbs doesn't.
This applies (I don't have a medium9) xlRangeAutoFormatAccounting4 in vba.
Selection.AutoFormat Format:=xlRangeAutoFormatAccounting4, Number:=True, _
Font:=True, Alignment:=True, Border:=True, Pattern:=True, Width:=True
So first look up constants in vba's object browser. xlRangeAutoFormatAccounting4 = 17
Then look the function up in object browser and look at the bottom for the function definition,.
Function AutoFormat([Format As XlRangeAutoFormat = xlRangeAutoFormatClassic1], [Number], [Font], [Alignment], [Border], [Pattern], [Width])
So the vba becomes in vbs (and vbs works in vba) (and as you can see you can work out the correct way without needing to look the function up usually)
Selection.AutoFormat 17, True, True, True,True, True, True
So your code becomes
objXLWs.Range("A3").CurrentRegion.Select.AutoFormat 17, True, True, True,True, True, True