I'm newbie in Visual Basic and I'm tring to build a simply application who perform some operation on an Excel file.
I want to edit the cell's border properties of my sheet, I need to edit the weight and the color of the separate border of some specified cells (for example only the bottom border or the top border).
Ifound some interesting resource on the web:
http://www.functionx.com/vbaexcel/cells/Lesson4.htm
Border around each cell in a range
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/93bb7ff7-0aed-4ce1-adca-aabde5fc3c2c
anyway is impossible to me to follow the suggested example.
This is an extract of my code:
Public Class mytest
Dim oExcel As Object 'Oggetto per la gestione del file Excel
Dim oBook As Object 'Oggetto per la gestione del file Excel
Dim page As Integer = 1 'Indice per la gestione dei fogli Excel
....
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Creazione nuovo workbook in Excel
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
'Add data to cells of the first worksheet in the new workbook
'Apertura file in lettura
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("input.csv")
MyReader.TextFieldType = FileIO.FieldType.Delimited
'Imposto il carattere di separazione tra i campi
MyReader.SetDelimiters(";")
'Creo stringa lettura righe
Dim currentRow As String()
'Leggo 1 volta per saltare
currentRow = MyReader.ReadFields()
'Fino alla fine del file
While Not MyReader.EndOfData
'Mostra riga nella label
lblShowElab.Text = page
Try
'Formatto i fogli
oBook.Worksheets(page).Range("A1:B1").Merge()
oBook.Worksheets(page).Range("A2:B2").Merge()
...
oBook.Worksheets(page).Range("B2").Borders(xlEdgeRight).LineStyle = xlContinuous
oBook.Worksheets(page).Range("B2").Borders(xlEdgeRight).Weight = xlThin
'Leggo riga per riga
currentRow = MyReader.ReadFields()
'Inserisco i campi di ogni riga nella cella voluta
oBook.Worksheets(page).Range("F2").Value = currentRow(14)
oBook.Worksheets(page).Range("A5").Value = currentRow(12)
...
'Incremento la pagina
page = page + 1
'Se la pagina e' maggiore di 3 la devo creare
If page > 3 Then
oBook.Worksheets.Add(After:=oBook.Worksheets(oBook.Worksheets.Count))
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
lblShowElab.Text = "Elaborazione Terminata"
End Using
'Salva il Workbook ed esce da Excel
oBook.SaveAs("output.xlsx")
oExcel.Quit()
End Sub
End Class
The commands
oBook.Worksheets(page).Range("B2").Borders(xlEdgeRight).LineStyle = xlContinuous
oBook.Worksheets(page).Range("B2").Borders(xlEdgeRight).Weight = xlThin
does not work for me becouse Visual Studio do not recognize and mark me the xlEdgeRight, xlContinuous, xlEdgeRight, xlThin variables and pretend that I declare this.
This commas are common on every example I found in Internet, I do not understand why not works for me. Had I missed some libraries or namespace to declare? What I need?
Hope someone can help me,
Regards, thaks a lot.
All the constants like xlEdgeRight, xlContinuous, xlEdgeRight, xlThin etc are just long integers.
You need to lookup their values and use them in your application.
Ideally you'd create a bunch of constants in your application so you can continue to use the named versions so its easier to understand your code.
The following page lists all the excel constants and their values. http://www.smarterdatacollection.com/Blog/?p=374
I assume there not tied to a specific excel version, but if they are you just need to lookup the ones for your version.
Related
I'm creating a code to download some material information, by first asking SAP to get a certain plant information. Then I'm switching the drill down to the Business Area (BA) and lastly I have to Drilldown each BA by Material Code.
Where I'm running into issues is when I'm making the Drilldown by Material Code (the second "for"), since each of the plants has a different number of Business Areas. Could you tell how can I know the number of rows of the first Business Area table?
The code also has to export the Material Code data to an excel sheet, but I didn't include that in the following code.
This is the code I'm using:
If Not IsObject(application) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set application = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(connection) Then
Set connection = application.Children(0)
End If
If Not IsObject(session) Then
Set session = connection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject session, "on"
WScript.ConnectObject application, "on"
End If
'Startup
session.findById("wnd[0]").maximize
'Variables
filepath = "30-06-2022" 'Poner la fecha del dia de descarga
CurrentDate = "07/2022" 'Poner el mes del analisis
PlantList = Array(NameOfAllThePlants)
'Search for MCBA
session.findById("wnd[0]/tbar[0]/okcd").text = "MCBA"
session.findById("wnd[0]").sendVKey 0
For i = 0 To 23 Step 1
'MCBA Parameters
session.findById("wnd[0]/usr/ctxtSL_WERKS-LOW").text = PlantList(i)
session.findById("wnd[0]/usr/ctxtSL_SPMON-LOW").text = "07/2022"
session.findById("wnd[0]/usr/ctxtSL_SPMON-HIGH").text = "07/2022"
session.findById("wnd[0]/usr/ctxtSL_SPMON-HIGH").setFocus
session.findById("wnd[0]/usr/ctxtSL_SPMON-HIGH").caretPosition = 7
session.findById("wnd[0]/tbar[1]/btn[8]").press
'Analysis Currency
session.findById("wnd[0]/tbar[1]/btn[31]").press
session.findById("wnd[1]/usr/sub:SAPLSPO4:0300/ctxtSVALD-VALUE[0,21]").text = "usd"
session.findById("wnd[1]/usr/sub:SAPLSPO4:0300/ctxtSVALD-VALUE[2,21]").text = "07/04/2022"
session.findById("wnd[1]/usr/sub:SAPLSPO4:0300/ctxtSVALD-VALUE[2,21]").setFocus
session.findById("wnd[1]/usr/sub:SAPLSPO4:0300/ctxtSVALD-VALUE[2,21]").caretPosition = 10
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Change drilldown to Business Area
session.findById("wnd[0]/tbar[1]/btn[7]").press
session.findById("wnd[1]/tbar[0]/btn[0]").press
For j = 0 To LastRowOfTheBusinessAreaTable
'Drilldown by MaterialCode
session.findById("wnd[0]/usr/lbl[1,"&Cstr(j+6)&"]").setFocus
session.findById("wnd[0]/usr/lbl[1,"&Cstr(j+6)&"]").caretPosition = 3
session.findById("wnd[0]").sendVKey 8
session.findById("wnd[1]/usr/sub:SAPLMCS2:0201/radLMCS2-MRKKZ[4,0]").select
session.findById("wnd[1]/usr/sub:SAPLMCS2:0201/radLMCS2-MRKKZ[4,0]").setFocus
session.findById("wnd[1]/tbar[0]/btn[0]").press
'back to Business Area view
session.findById("wnd[0]/tbar[0]/btn[3]").press
session.findById("wnd[0]/usr/lbl[1,7]").setFocus
session.findById("wnd[0]/usr/lbl[1,7]").caretPosition = 7
session.findById("wnd[0]").sendVKey 8
'session.findById("wnd[1]/usr/sub:SAPLMCS2:0201/radLMCS2-MRKKZ[4,0]").setFocus
session.findById("wnd[1]/tbar[0]/btn[0]").press
Next
'back
session.findById("wnd[0]/tbar[0]/btn[3]").press
'don't save
session.findById("wnd[1]/usr/btnSPOP-OPTION2").press
I have a standard List View component using checkboxes, while populating its data I would like to remove the checkboxes of specific rows based on a criteria, at this moment I found no way of doing it and no alternative component to replace the listview and include checkboxes.
Private Sub Form_Load()
Dim clmX As ColumnHeader
Dim itmX As ListItem
Dim i As Integer
For i = 1 To 3
Set clmX = ListView1.ColumnHeaders.Add()
clmX.Text = "Column " & i
Next i
' Inclui 10 items com o mesmo ícone
For i = 1 To 10
Set itmX = ListView1.ListItems.Add()
itmX.SmallIcon = 1
itmX.Text = "ListItem " & i
itmX.SubItems(1) = "Subitem 1"
itmX.SubItems(2) = "Subitem 2"
If i = 2 Then
'here
'itmX.removeCheckbox
End If
Next i
End Sub
I'm trying to add records to an exisiting table called "Topics" (section as of "For Each SelectedTopic In SelectedTopicsCtl.ItemsSelected" in the code below).
When executing the code i always get "Run-time error '3022': The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. So it goes wrong at the creation of the Autonumber in the field "ID" (= the only field that is indexed - no duplicates).
When debugging, line "TopicRecord.Update" in the code below is highlighted.
I have read several posts on this topic on this forum and on other forums but still cannot get this to work - i must be overlooking something....
Private Sub Copy_Click()
Dim JournalEntrySourceRecord, JournalEntryDestinationRecord, TopicRecord As Recordset
Dim JournalEntryToCopyFromCtl, JournalEntryToCopyToCtl, JournalEntryDateCreatedCtl, SelectedTopicsCtl As Control
Dim Counter, intI As Integer
Dim SelectedTopic, varItm As Variant
Set JournalEntryToCopyFromCtl = Forms![Copy Journal Entry]!JournalEntryToCopyFrom
Set JournalEntryToCopyToCtl = Forms![Copy Journal Entry]!JournalEntryToCopyTo
Set JournalEntryDateCreatedCtl = Forms![Copy Journal Entry]!JournalEntryDateCreated
Set JournalEntrySourceRecord = CurrentDb.OpenRecordset("Select * from JournalEntries where ID=" & JournalEntryToCopyFromCtl.Value)
Set JournalEntryDestinationRecord = CurrentDb.OpenRecordset("Select * from JournalEntries where ID=" & JournalEntryToCopyToCtl.Value)
Set SelectedTopicsCtl = Forms![Copy Journal Entry]!TopicsToCopy
Set TopicRecord = CurrentDb.OpenRecordset("Topics", dbOpenDynaset, dbSeeChanges)
With JournalEntryDestinationRecord
.Edit
.Fields("InitiativeID") = JournalEntrySourceRecord.Fields("InitiativeID")
.Fields("DateCreated") = JournalEntryDateCreatedCtl.Value
.Fields("Comment") = JournalEntrySourceRecord.Fields("Comment")
.Fields("Active") = "True"
.Fields("InternalOnly") = JournalEntrySourceRecord.Fields("InternalOnly")
.Fields("Confidential") = JournalEntrySourceRecord.Fields("Confidential")
.Update
.Close
End With
JournalEntrySourceRecord.Close
Set JournalEntrySourceRecord = Nothing
Set JournalEntryDestinationRecord = Nothing
For Each SelectedTopic In SelectedTopicsCtl.ItemsSelected
TopicRecord.AddNew
For Counter = 3 To SelectedTopicsCtl.ColumnCount - 1
TopicRecord.Fields(Counter) = SelectedTopicsCtl.Column(Counter, SelectedTopic)
Next Counter
TopicRecord.Fields("JournalEntryID") = JournalEntryToCopyToCtl.Value
TopicRecord.Fields("DateCreated") = JournalEntryDateCreatedCtl.Value
TopicRecord.Update
Next SelectedTopic
TopicRecord.Close
Set TopicRecord = Nothing
End Sub
First, your Dims won't work as you expect. Use:
Dim JournalEntrySourceRecord As Recordset
Dim JournalEntryDestinationRecord As Recordset
Dim TopicRecord As Recordset
Second, it looks like you get your ID included here:
TopicRecord.Fields(Counter)
or Topic is a query that includes it somehow. Try to specify the fields specifically and/or debug like this:
For Counter = 3 To SelectedTopicsCtl.ColumnCount - 1
TopicRecord.Fields(Counter).Value = SelectedTopicsCtl.Column(Counter, SelectedTopic)
Debug.Print Counter, TopicRecord.Fields(Counter).Name
Next Counter
wondering if someone can help me out with the following problem.
I have staff stock areas with items regularly. As part of the stocking they are required to also charge whatever they send out. The issue is that when they charge they do the repetitive task of data entry for each item they charge out.
In my ideal setup, they can scan a barcode and the task would be completed in seconds since the barcode would contain all the data that needs to be entered.
To automate this, I was thinking of creating one barcode that can capture all the required inputs along with the tab, and enter keys they are required to input And then when the barcode is scanned from a paper print out the info would be automatically charged.
The data driving the barcode is in Excel so I'd like to create the barcode in Excel. This is where I need help, I've tried to add barcode font but it's not working and I have no experience in VBA if that is required.Any guidance would be much appreciated!
You may use barcode generation component to generate barcodes from VBA (as pictures) and insert these pictures into Excel.
Below is the sample code for ByteScout BarCode SDK (commercial component compatible with VBA) sample. Basically, if you want you may replace it with any other component that is capable of creating pictures when called from VBA.
' IMPORTANT: This demo uses VBA so if you have it disabled please temporary enable
' by going to Tools - Macro - Security.. and changing the security mode to ""Medium""
' to Ask if you want enable macro or not. Then close and reopen this Excel document
' You should have evaluation version of the ByteScout SDK installed to get it working - get it from https://bytescout.com
' If you are getting error message like
' "File or assembly named Bytescout SDK, or one of its dependencies, was not found"
' then please try the following:
'
' - Close Excel
' - (for Office 2003 only) download and install this hotfix from Microsoft:
' http://www.microsoft.com/downloads/details.aspx?FamilyId=1B0BFB35-C252-43CC-8A2A-6A64D6AC4670&displaylang=en
'
' and then try again!
'
' If you have any questions please contact us at http://bytescout.com/support/ or at support#bytescout.com
'==============================================
'References used
'=================
'Bytescout Barcode SDK
'
' IMPORTANT:
' ==============================================================
'1) Add the ActiveX reference in Tools -> References
'2) Loop through the values from the Column A for which barcode has to be generated
'3) Parse the value to Bytescout Barcode Object to generate the barcode using QR Code barcode type.
'4) Save the generated Barcode Image
'5) Insert the Barcode Image in the Column B
'6) Repeat the steps 3 to 5 till the last Value in Column A
'
'==================================================================
Option Explicit
' declare function to get temporary folder (where we could save barcode images temporary)
Declare Function GetTempPath _
Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, _
ByVal lpBuffer As String) As Long
' function to return path to temporary folder
Public Function fncGetTempPath() As String
Dim PathLen As Long
Dim WinTempDir As String
Dim BufferLength As Long
BufferLength = 260
WinTempDir = Space(BufferLength)
PathLen = GetTempPath(BufferLength, WinTempDir)
If Not PathLen = 0 Then
fncGetTempPath = Left(WinTempDir, PathLen)
Else
fncGetTempPath = CurDir()
End If
End Function
Sub Barcode_Click()
'Fetch the Worksheet
Dim mySheet As Worksheet
Set mySheet = Worksheets(1) 'Barcode_Data Sheet
'temp path to save the Barcode images
Dim filePath As String
filePath = fncGetTempPath() 'Change the Path But should end with Backslash( \ )
'Prepare the Bytescout Barcode Object
'====================================
Dim myBarcode As New Bytescout_BarCode.Barcode
myBarcode.RegistrationName = "demo" 'Change the name for full version
myBarcode.RegistrationKey = "demo" 'Change the key for full version
'Barcode Settings
myBarcode.Symbology = SymbologyType_QRCode ' QR Code barcode, you may change to other barcode types like Code 39, Code 128 etc
' set barcode image quality resolution
myBarcode.ResolutionX = 300 'Resolution higher than 250 is good for printing
myBarcode.ResolutionY = 300 'Resolution higher than 250 is good for printing
myBarcode.DrawCaption = True 'Showing Barcode Captions in the Barcode Image
myBarcode.DrawCaptionFor2DBarcodes = True ' show captions for 2D barcodes like QR Code
' first clean the B column from old images (if any)
Dim Sh As Shape
With mySheet
For Each Sh In .Shapes
If Not Application.Intersect(Sh.TopLeftCell, .Range("B1:B50")) Is Nothing Then
If Sh.Type = msoPicture Then Sh.Delete
End If
Next Sh
End With
' now generate new barcodes and insert into cells in the column B
' Repeat the steps for each row from 2 to 6
Dim myVal As Integer
For myVal = 2 To 6 'change the code to all rows with values
'Parse the Value from the Column A to Bytescout Barcode Object
myBarcode.Value = mySheet.Cells(myVal, 1).Text
'Fit the barcode into 80X30 mm rectangle
myBarcode.FitInto_3 80, 30, 4 '4 refers to units of measurement as millimeter
'Save the barcode image to a file in temporary folder
myBarcode.SaveImage filePath & "myBarcode" & myVal & ".png"
'Insert the Barcode image to the Column B and resize them to fit the cell.
'==========================================================================
With mySheet.Pictures.Insert(filePath & "myBarcode" & myVal & ".png")
.ShapeRange.LockAspectRatio = True ' lock aspect ratio
.Left = mySheet.Cells(myVal, 2).Left + 1 ' set left
.Top = mySheet.Cells(myVal, 2).Top + 1 ' set right
.PrintObject = True ' allow printing this object
.Placement = xlMove ' set placement mode to move but do not resize with the cell
.ShapeRange.ScaleHeight 1, True ' set height scale to 1 (no scale)
.ShapeRange.ScaleWidth 1, True ' set width scale to 1 (no scale)
End With
Next myVal ' move to next cell in the column
' Release the Barcode Object.
Set myBarcode = Nothing
End Sub
Disclaimer: I'm relatd to ByteScout
I'm very new (1 week) to visual basic and basically I'm trying to automate some repetitive work, now to the point , within a number of files produced with varying data I need to format the selected range as a table (medium 9) but i'm in a block at the moment and need some help and would really appreciate it, here is what i have so far>>>>
Option Explicit
Dim strDate, strRepDate, strPath, strPathRaw , strDate2
dim dteTemp, dteDay, dteMth, dteYear, newDate, myDate
myDate = Date()
dteTemp = DateAdd("D", -1, myDate)
dteDay = DatePart("D", dteTemp)
dteMth = DatePart("M", dteTemp)
dteYear = DatePart("YYYY", dteTemp)
If (Len(dteDay) = 1) Then dteDay = "0" & dteDay
If (Len(dteMth) = 1) Then dteMth = "0" & dteMth
strDate = dteYear&"-"&dteMth&"-"&dteDay
strDate2 = dteYear&""&dteMth&""&dteDay
Dim objXLApp, objXLWb, objXLWs
Set objXLApp = CreateObject("Excel.Application")
Set objXLWb = objXLApp.Workbooks.Open("C:\Users\CuRrY\Desktop\"&strDate2&"\Agent Daily Disposition "&strDate2&".xls")
objXLApp.Application.Visible = True
'start excell
Set objXLWs = objXLWb.Sheets(1)
'objXLWs.Cells(Row, Column ).Value
With objXLWs
objXLWs.Cells(3, 1).Value = "Agent Name"
'objXLWs.Range("A3").Select
objXLWs.Range("A3").CurrentRegion.Select
'End With
as you can see i reached as far as CurrentRegion.Select but how to format selected cells into (medium 9) i've tried so much and failed
Thanks for any help
You can configure the CurrentRegion(which represents a Range object) through the SpecialCells Submethod. Although your conditions are specific to your xls sheet, you will still have to follow the formatting available through the specialcells() method properties. Also, by utilizing the currentregion property, the page assumes you have a xls header. So it is important to verify your table structure before trying to incorporate this property.
For instance:
Sub FillIn()
Range("A1").CurrentRegion.SpecialCells(xlCellTypeBlanks).FormulaR1C1 _
= "=R[-1]C"
Range("A1").CurrentRegion.Value = Range("A1").CurrentRegion.Value
End Sub
View the available properties that can be applied to CurrentRegion -> Here
And the MSDN Article -> Here